01 matplotlib_pyplot

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들을 보면

    • plot: 대표적인 함수루 축을 기준으로 선을 그림 (Plot lines and/or markers to the Axes)
    • bar:Make a bar plot.
    • scatter:Make a scatter plot of x vs y.
    • hist:Plot a histogram.
    • boxplot:Make a box and whisker plot.
    • stackplot:Draws a stacked area plot.
    • pie:Plot a pie chart.
  • 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]:
sepal lengthsepal widthpetal lengthpetal widthtargetspecies
05.13.51.40.20.0setosa
14.93.01.40.20.0setosa
24.73.21.30.20.0setosa
34.63.11.50.20.0setosa
45.03.61.40.20.0setosa

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]:
sepal lengthsepal widthpetal lengthpetal widthtarget
meanmeanmeanmeanmean
species
setosa5.0063.4181.4640.2440.0
versicolor5.9362.7704.2601.3261.0
virginica6.5882.9745.5522.0262.0

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]:
[<matplotlib.lines.Line2D at 0x7fe358a59ba8>]

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]:
sepal lengthsepal widthpetal lengthpetal widthtarget
meanmeanmeanmeanmean
species
setosa5.0063.4181.4640.2440.0
versicolor5.9362.7704.2601.3261.0
virginica6.5882.9745.5522.0262.0
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()


© 2017. All rights reserved.

Powered by ZooFighter v0.12