seabornの導入
以下の記事で話題になっていたので,自分も導入してみました.
seabornは,installして読みこむだけで,デフォルトでは少々野暮ったい感じのmatplotlibをいい感じにしてくれるライブラリです.
公式のドキュメント
基本的には,公式のギャラリーに行き,書きたいグラフを探して使うのがいいと思います.
install
pip install seaborn
サンプル
ipython notebook環境で行う場合は,以下のコードを打つことでインライン出力できます.
%matplotlib inline
import
import numpy as np import matplotlib.pyplot as plt import seaborn as sns
関数
seabornをimportしただけで自動的にスタイルが適用されるようです.
fig = plt.figure(figsize=(16, 4)) ax = fig.add_subplot(1, 3, 1) ax.set_title('y = x') x = np.linspace(-5, 5, 100) ax.plot(x, x) ax = fig.add_subplot(1, 3, 2) ax.set_title('y = x^2') x = np.linspace(-5, 5, 100) ax.plot(x, x**2) ax = fig.add_subplot(1, 3, 3) ax.set_title('y = sin(x)') x = np.linspace(-10, 10, 100) ax.plot(x, np.sin(x))
標準正規分布
x = np.random.randn(1000)
sns.distplot(x)
ランダムウォーク
n = 1000 x = np.linspace(0, n, n) step = np.random.choice([1, -1], n) pos = np.cumsum(step) plt.plot(x, pos)
線形回帰
簡単な線形回帰の例です.
from sklearn.linear_model import LinearRegression N = 100 x = np.linspace(0, 10, N) noise = np.random.randn(N) y = x + noise X = [[i] for i in x] lr = LinearRegression() lr.fit(X, y) y_predicted = lr.predict(X) plt.scatter(X, y) plt.title('Linear Regression') plt.plot(X, X, label='actual: y = x') plt.plot(X, y_predicted, label='predicted: y = %.4f + %.4fx' % (lr.intercept_, lr.coef_)) plt.legend(loc=2)
iris
sns.pairplot()を使うことで一度に散布図がプロットできます(かなり便利!!!).
pandasのDataFrameを使うことが前提らしいです.
from sklearn import datasets import pandas as pd iris = datasets.load_iris() df = pd.DataFrame(data=iris.data, columns=iris.feature_names) df['target'] = iris.target sns.pairplot(data=df, hue='target', vars=iris.feature_names)