今天我們來了解一下一張圖的生命周期绑蔫,每張圖的可視化過程中都經(jīng)歷了什么焕刮,以便更深入地理解matplotlib关炼。
Object-Oriented API vs Pyplot
matplotlib有兩種接口围来,第一種是面向?qū)ο蟮慕涌谕炊猓抢靡粋€figure.Figure
實例上的axes.Axes
實例來渲染圖像的刺桃。
第二種是MATLAB風格的接口粹淋,被封裝在pyplot模塊當中妈候。
重點關注兩點:
- Figure是最終的圖像避凝,其上包含1個或多個Axes
- Axes代表一個獨立的圖(plot),主要不要將其與“axis”混淆蹂析,后者指的是一個plot的x/y坐標軸
盡量使用面向?qū)ο蟮慕涌诙皇莗yplot接口葛碧,這樣我們可以調(diào)用直接從Axes類畫圖的方法借杰,它在我們定制化圖形時能夠賦予我們更多的靈活性。
準備數(shù)據(jù)
data = {'Barton LLC': 109438.50,
'Frami, Hills and Schmidt': 103569.59,
'Fritsch, Russel and Anderson': 112214.71,
'Jerde-Hilpert': 112591.43,
'Keeling LLC': 100934.30,
'Koepp Ltd': 103660.54,
'Kulas Inc': 137351.96,
'Trantow-Barrows': 123381.38,
'White-Trantow': 135841.99,
'Will LLC': 104437.60}
group_data = list(data.values())
group_names = list(data.keys())
group_mean = np.mean(group_data)
這是一組多家企業(yè)的銷售信息數(shù)據(jù)进泼,適合用來畫柱形圖蔗衡。
我們要使用面向?qū)ο蟮慕涌趤懋媹D,首先生成一個figure.Figure和axes.Axes的實例乳绕,F(xiàn)igure就相當于一張畫布绞惦,而Axes就是畫布當中的一塊區(qū)域,我們在其中渲染特定的圖形洋措。
fig, ax = plt.subplots()
有了Axes實例后济蝉,我們就可以在上面畫圖了。
ax.barh(group_names, group_data)
風格控制
matplotlib中有多種風格
print(plt.style.available)
['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'seaborn', 'Solarize_Light2', 'tableau-colorblind10', '_classic_test']
通過如下命令激活風格
plt.style.use('fivethirtyeight')
和之前的圖比較一下,
定制圖形
現(xiàn)在我們有了一般化的圖形王滤,我們可以在此基礎上進行微調(diào)贺嫂,使其達到我們想要的效果。首先將x-axis的label進行旋轉(zhuǎn)淑仆。
fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
接下來涝婉,為圖像加標題
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
我們還可以通過pyplot.subplots()函數(shù)調(diào)整圖像大小哥力。
fig, ax = plt.subplots(figsize=(8, 4))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
我們可以通過 ticker.FuncFormatter
類自定義label 的格式蔗怠。下面的例子中定義了一個函數(shù),該函數(shù)接受一個整數(shù)吩跋,返回一個字符串:
def currency(x, pos):
"""The two args are the value and tick position"""
if x >= 1e6:
s = '${:1.1f}M'.format(x*1e-6)
else:
s = '${:1.0f}K'.format(x*1e-3)
return s
formatter = FuncFormatter(currency)
fig, ax = plt.subplots(figsize=(8, 4))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
ax.xaxis.set_major_formatter(formatter)
組合圖形
可以在一個Axes實例上渲染不同的圖形寞射。
fig, ax = plt.subplots(figsize=(8, 4))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')
ax.axvline(group_mean, ls='--', color='r')
# Annotate new companies
for group in [3, 5, 8]:
ax.text(145000, group, "New Company", fontsize=10,
verticalalignment="center")
# Now we'll move our title up since it's getting a little cramped
ax.title.set(y=1.05)
ax.set(xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company',
title='Company Revenue')
ax.xaxis.set_major_formatter(formatter)
ax.set_xticks([0, 25e3, 50e3, 75e3, 100e3, 125e3])
plt.show()
保存圖片
fig.savefig('sales.png', transparent=False, dpi=80, bbox_inches="tight")