01 與圖片的交互方式設置
這一小節簡要介紹一下Matplotlib的交互方式
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(111)
X = np.random.rand(1000)
y = np.random.rand(1000)
# 圖表窗口1 → plt.show()
plt.plot(X)
plt.show()
# 直接生成圖表
# 圖表窗口2 → 魔法函數,嵌入圖表
% matplotlib inline
plt.scatter(X, y)
# 直接嵌入圖表,不用plt.show()
# <matplotlib.collections.PathCollection at ...> 代表該圖表對象
# 圖表窗口3 → 魔法函數,彈出可交互的matplotlib窗口,缺點是特別佔內存
% matplotlib notebook
s = pd.Series(X)
s.plot(style = 'k--o',figsize=(10,5))
# 可交互的matplotlib窗口,不用plt.show()
# 可做一定調整
# 圖表窗口4 → 魔法函數,彈出matplotlib控制檯,這種情況下就不是嵌入在網頁中了,而是有單獨的GUI
% matplotlib qt5
df = pd.DataFrame(np.random.rand(50,2),columns=['A','B'])
df.hist(figsize=(12,5),color='g',alpha=0.8)
# 可交互性控制檯
# 如果已經設置了顯示方式(比如notebook),需要重啓然後再運行魔法函數
# 網頁嵌入的交互性窗口 和 控制檯,只能顯示一個
#plt.close()
# 關閉窗口
#plt.gcf().clear()
# 每次清空圖表內內容
02 座標軸的刻度、圖中的網格設置
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(11)
df = pd.DataFrame(np.random.rand(10, 2), columns=['A', 'B'])
df
A | B | |
---|---|---|
0 | 0.180270 | 0.019475 |
1 | 0.463219 | 0.724934 |
2 | 0.420204 | 0.485427 |
3 | 0.012781 | 0.487372 |
4 | 0.941807 | 0.850795 |
5 | 0.729964 | 0.108736 |
6 | 0.893904 | 0.857154 |
7 | 0.165087 | 0.632334 |
8 | 0.020484 | 0.116737 |
9 | 0.316367 | 0.157912 |
fig = plt.figure(figsize=(10, 2))
print(fig, type(fig))
Figure(720x144) <class 'matplotlib.figure.Figure'>
<Figure size 720x144 with 0 Axes>
fig = df.plot(kind='bar')
plt.title('df') # 設置表的標題
plt.xlabel('x') # 設置x軸
plt.ylabel('y', rotation=360) # 設置y軸,rotation可以將label轉到合適的角度
plt.legend(loc='best') # 設置圖例顯示在圖的哪一邊
# 可選值如下
# best
# upper right
# upper left
# lower left
# lower right
# right
# center left
# center right
# lower center
# upper center
# center
plt.xlim(0, 12) # 設置x軸的長度,輸入兩個數a,b,表示x從a到b
plt.ylim(0, 1.2) # 設置y軸的長度,輸入兩個數a,b,表示x從a到b
plt.xticks(range(12), rotation=360) # 設置x軸的刻度,輸入是列表或者range數據結構;設置rotation
plt.yticks(np.linspace(0, 1.2, 11))
# 爲原本的座標刻度設置‘label’,同理y軸也可以這麼設置
fig.set_xticklabels(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']);

x = np.linspace(-np.pi, np.pi, 256, endpoint=True)
a, b = np.cos(x), np.sin(x)
plt.plot(x, a, '--', label='cos')
plt.plot(x, b, label='sin') # 要想顯示圖例需要設置label屬性,然後再利用legend方法顯示
plt.legend(loc='best')
# x和y座標軸刻度顯示的方式,'inout'正好插入座標軸,'in'朝內,'out'朝外
plt.rcParams['xtick.direction'] = 'out'
plt.rcParams['ytick.direction'] = 'inout'
#座標軸的刻度是否顯示,如果顯示則是True,若是不顯示,則是False
plt.tick_params(bottom=True, left=False, right=True, top=True)
plt.grid(True, linestyle='--', color='purple', axis='both')
frame = plt.gca()
# plt.axis('off') # 整個關閉座標軸
# 關閉座標軸
frame.axes.get_xaxis().set_visible(True) # 設置座標軸是否可見
frame.axes.get_yaxis().set_visible(True) # True可見,False不可見