1. 程式人生 > >python資料分析基礎之圖與圖表——多圖並列

python資料分析基礎之圖與圖表——多圖並列

#_author:"zhengly"
#date:2018/8/30
'''
除了使用matplotlib建立標準統計圖,還可以使用panda來建立其他型別的統計圖
本例實現:利用panda建立一個條形圖和箱線圖,並將它們並排放置
'''
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
#建立一個基礎圖和兩個子圖
fig,axes=plt.subplots(nrows=1,ncols=2)
#使用ravel()函式將兩個子圖分別賦給兩個變數ax1和ax2,這樣可以避免是使用行和列的索引
ax1,ax2 = axes.ravel()
data_frame = pd.DataFrame(np.random.rand(5,3),index=['Customer 1','Customer 2','Customer 3','Customer 4','Customer 5'],
                          columns=pd.Index(['Metric 1','Metric 2','Metric 3'],name='Metric'))
#建立條形圖並設定相關屬性
data_frame.plot(kind='bar',ax=ax1,alpha=0.75,title='Bar Plot')
plt.setp(ax1.get_xticklabels(),rotation=45,fontsize=10)
plt.setp(ax1.get_yticklabels(),rotation=0,fontsize=10)
ax1.set_xlabel('Customer')
ax1.set_ylabel('Value')
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('left')
#建立箱線圖並設定相關屬性
colors = dict(boxes='DarkBlue',whiskers='Gray',medians='Red',caps='Black')
data_frame.plot(kind='box',color=colors,sym='r.',ax=ax2,title='Box Plot')
plt.setp(ax2.get_xticklabels(),rotation=45,fontsize=10)
plt.setp(ax2.get_yticklabels(),rotation=0,fontsize=10)
ax2.set_xlabel('Metric')
ax2.set_ylabel('Value')
ax2.xaxis.set_ticks_position('bottom')
ax2.yaxis.set_ticks_position('left')
plt.savefig('pandas_plots.png',dpi=400,bbox_inches='tight')
plt.show()