matplotlib繪圖基礎(3)—— 一張圖的圖生歷程

今天我們來了解一下一張圖的生命周期,每張圖的可視化過程中都經(jīng)歷了什么,以便更深入地理解matplotlib。

Object-Oriented API vs Pyplot

matplotlib有兩種接口,第一種是面向?qū)ο蟮慕涌冢抢靡粋€figure.Figure實例上的axes.Axes實例來渲染圖像的。
第二種是MATLAB風格的接口,被封裝在pyplot模塊當中。
重點關(guān)注兩點:

  • 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")
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容