01 matplotlib_pyplot
| 42 Minute Read on Visualization
matplot_pyplot¶
- matplotlib은 파이썬에서 데이터를 시각화하는 대표적인 패키지이다.
- pyplot은 matplotlib의 하위라이브러로 Bar, Scatter, Historgam, Box 같은 Plot을 쉽게 사용 할 수 있게 해준다. (The matplotlib.pyplot module contains, functions that allow you to generate many kinds of plots quickly)
The matplotlib.pyplot docs 를 보면 130여개의 function을 제공하는데 대표적인 function들을 보면
DataFrame.plot은 DataFrame의 메소드로 DataFrame에서 편하게 matplotlib 함수들을 호출하게 해준다.DataFrame.plot docs
- kind라는 매개변수를 통해서 그래프이 형태를 선택할 있다.
- 그래프의 형태에 따라 수많은 매개변수가 존재한다.
In [1]:
from sklearn import datasets
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
iris = datasets.load_iris()
df = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
columns= iris['feature_names'] + ['target'])
df = df.rename(columns={'sepal length (cm)': 'sepal length', 'sepal width (cm)': 'sepal width'
,'petal length (cm)': 'petal length','petal width (cm)': 'petal width'})
dict_iris = {0.0:'setosa', 1.0:'versicolor', 2.0:'virginica'}
df['species'] = df['target'].map(dict_iris)
df.head()
Out[1]:
plot¶
In [2]:
plt.plot(df['sepal length'])
plt.show()
In [3]:
#DataFrame.plot로 호출
df.plot() # kind ='line' 가 생략
#df.plot(kind = 'line')
plt.show()
In [ ]:
In [4]:
tuple_dic = ['mean']
grby = df.groupby(['species']).agg(tuple_dic)
grby
Out[4]:
Bar¶
In [5]:
plt.bar('target','sepal length', data = df)
plt.show()
In [6]:
#barh는 수평으로 보여줌
plt.barh('target','sepal length', data = df)
plt.show()
In [7]:
#DataFrame.plot로 호출
grby.plot(kind = 'bar')
plt.show()
scatter¶
In [9]:
plt.scatter('sepal length', 'sepal width', data = df )
plt.plot(grby['sepal length'].values)
Out[9]:
hist¶
In [10]:
plt.hist('sepal width', data =df)
plt.show()
In [11]:
#DataFrame.plot로 호출
df.hist()
plt.show()
boxplot¶
In [12]:
plt.boxplot('sepal width', data = df )
plt.show()
In [13]:
df.plot(kind = 'box')
plt.show()
pie¶
In [14]:
plt.pie('sepal length', data = grby)
plt.show()
stackplot¶
In [15]:
grby.head()
Out[15]:
In [16]:
plt.stackplot(df['target'], df['sepal length'], df['sepal length'])
plt.show()
In [17]:
plt.stackplot(df.index, df['sepal length'], df['sepal length'])
plt.show()
In [18]:
df.plot(kind = 'area')
plt.show()
In [19]:
# seaborn 패키지를 사용하면 기본 matplotlib 보다는 좀더 좋은 그래프를 그릴 수 있다.
In [20]:
sns.jointplot(x="sepal width", y="sepal length", data=df, size=5)
sns.pairplot(df.drop("target", axis=1), hue="species", size=3, diag_kind="kde")
plt.show()