02 figure_axes
| 29 Minute Read on Visualization
Figure_Axes¶
- matplotlib을 사용하여 그림을 그리기 위해서 기본적으로 Figure(windows(창)의 개념) 객체와 Figure 객체에 포함되는 하나 이상의 Axes(subplot)를 생성해야 한다.
- matplotlib.pyplot의 하위 함수나 DataFrame.plot 메소드를 호출할때는 자동으로 하나의 Figure와 Axes가 생성이 된다.
- Figure객체와 Axes객체는 여러개의 subplot을 관리할때 생성한다.
- Figure Docs에 보면 Figure는 모든 plot의 모든 요소를 포함하는 최상위 객체이다. (the figure module provides the top-level Artist, the Figure, which contains all the plot elements)
- Axes Docs에 보면 Axes는 Figure의 대부분의 기능을 가지고 있으며(The Axes contains most of the figure element) Axis, Tick, Line2D, Text, Polygon 같은 속성을 조정한다.
- Figure와 Axes관련 중요 함수를 보면
- pyplot.subplot docs를 보면 subplot함수는 Axes 객체를 반환한다. subplot은 nrows, ncols, plot_number의 순서대로 인수를 같는다.
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]:
In [2]:
ax1 = plt.subplot(2, 1, 1)
plt.plot('sepal length', data = df)
ax2 = plt.subplot(2, 1, 2)
plt.plot('petal length', data = df)
plt.show()
In [3]:
ax1 = plt.subplot(1, 2, 1)
plt.plot('sepal length', data = df)
ax2 = plt.subplot(1, 2, 2)
plt.scatter('petal length','sepal length', data = df)
plt.show()
In [ ]:
In [4]:
tuple_dic = ['mean']
grby3 = df.groupby(['species']).agg(tuple_dic).reset_index()
grby3
Out[4]:
In [5]:
fig, (ax0, ax1) = plt.subplots(nrows=1,ncols=2, sharey=True, figsize=(7, 4))
grby3.plot(kind='barh', y="sepal length", x="species", ax=ax0)
ax0.set_xlabel('sepal length')
avg = grby3['sepal length'].mean()
ax0.axvline(x=5, color='b', label='Average', linestyle='--', linewidth=1)
print(avg)
grby3.plot(kind='barh', y="petal length", x="species", ax=ax1)
ax1.set_xlabel('petal length')
avg = grby3['petal length'].mean()
ax1.axvline(x=2, color='b', label='Average', linestyle='--', linewidth=1)
plt.show()
In [6]:
ax2 = fig.add_subplot(3,1,3)
plt.show()
In [7]:
plt.show()
In [8]:
df = df.iloc[:,:4]
fig, axes = plt.subplots(nrows=4, ncols=1)
for i, c in enumerate(df.columns):
df[c].plot(kind='bar', ax=axes[i], figsize=(18, 12), title=c)
plt.show()
In [9]:
fig, axes = plt.subplots(nrows=4, ncols=1)
for i, c in enumerate(df.columns):
df[c].plot(kind='line', ax=axes[i], figsize=(18, 12), title=c)
plt.show()
In [ ]: