1. 程式人生 > >matplotlib 入門之The Lifecycle of a plot

matplotlib 入門之The Lifecycle of a plot

可能 posit tutorials 自動 strip ... tel currency lib

目錄

  • Note
  • 數據
  • 準備開始
  • 操控風格
    • 我錯了!!!
  • 定制圖像
  • 特別註意!!! figsize=(width, height)!!!
  • 格式化標簽
  • 組合多個可視化對象?
  • 保存你的圖片
  • transparent = True, 背景色設置為透明,如果支持的話
  • dpi: 控制解析度(dots per square inch)
  • bbox_inches="tight" fits the bounds of the figure to our plot.

matplotlib教程學習筆記

這篇教程旨在展示如何開始、完善、結束可視化過程。我們將以一些原始的數據為開端,以保存可視化的圖片為結尾。在其過程中,我們會展示一些整潔的特性和實用的練習。

Note

  • figure對象是圖片的最終體,可能包含1個或多個Axes對象
  • Axes對象代表獨立的plot,請不要把它和axis(坐標軸)混淆

數據


# sphinx_gallery_thumbnail_number = 10
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

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)

準備開始

第一步,我們先創建一個figure對象和axes對象,subplots可以替我們完成這項工作。

fig, ax = plt.subplots()

技術分享圖片

第二步,現在我們已經有了一個Axes實例,可以開始著手在上面“作畫”了。

ax.barh(group_names, group_data) #水平柱狀圖

技術分享圖片

操控風格

matplotlib擁有許多的繪圖風格,我們可以通過plt.style來查看。

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']
style = plt.style.available
n = len(style)

fig, axs = plt.subplots( n // 4 + 1, 4, figsize=(10, 20), sharex='all', sharey='all')# n//4+1 * 4 個axes    
#figsize=(width,height)!!! 像素大小為width*10 * height*10
count = 0
try:
    for i in range( n // 4 +1):
        for j in range(4):
            count += 1
            if count == n:
                raise ValueError
            plt.style.use(style[count])
            axs[i, j].barh(group_names, group_data)
            axs[i, j].set_title(style[count])


except ValueError: pass

plt.show()

技術分享圖片

風格控制背景色,線寬等許多特性(雖然我從上圖沒看出什麽來)。

我錯了!!!

經過實驗,發現plt.style.use語句必須在fig對象創建前,而且這個style好像只能統管整個fig,所以我試圖一個fig不同Axes不同style的計劃就這麽失敗了。不知道有什麽辦法能夠解救一下。
技術分享圖片

定制圖像

我已經擁有了比較普通的圖像, 我們可以為其添加一些微妙的有趣的變化。比方說,讓x軸的標簽旋轉。

首先,我們要獲得x軸上的標簽

fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()

使用pyplot.setp()函數可以便捷地調整屬性

fig, ax = plt.subplots()
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')

技術分享圖片

使用

plt.rcParams.update({'figure.autolayout': True})

命令matplotlib來自動排版,使得字體不要超出(可能由於後端的問題,測試圖片並沒有出現這種情況。)

接下來,我們使用axes.Axes.set()來為Axes添加標題等屬性,當然,這項工作也可以由setp()來完成。


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')
#plt.setp(ax, xlim=[-10000, 140000], xlabel='Total Revenue', ylabel='Company', title='Company Revenue')

技術分享圖片

特別註意!!! figsize=(width, height)!!!

特別註意,figsize屬性是widthheight, 與像素的關系是(width10) * (height*10),是10倍關系。

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')

技術分享圖片

格式化標簽

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)  #通過FuncFormatter可以定制標簽
fig, ax = plt.subplots(figsize=(6, 8))
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)

技術分享圖片

組合多個可視化對象?

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   , 8))
ax.barh(group_names, group_data)
labels = ax.get_xticklabels()
plt.setp(labels, rotation=45, horizontalalignment='right')

# Add a vertical line, here we set the style in the function call
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])
fig.subplots_adjust(left=0.3, right=0.8)  #感覺改了啊,跟例子的不一樣了 left,right後面的地方估計直接都是從左往右計了吧

plt.show()

[圖片上傳中...(image.png-5931a1-1552124449964-0)]

保存你的圖片

# fig.savefig('sales.png', transparent=False, dpi=80, bbox_inches="tight")

transparent = True, 背景色設置為透明,如果支持的話

dpi: 控制解析度(dots per square inch)

bbox_inches="tight" fits the bounds of the figure to our plot.

支持哪些格式呢

print(fig.canvas.get_supported_filetypes())
{'ps': 'Postscript', 'eps': 'Encapsulated Postscript', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'jpg': 'Joint Photographic Experts Group', 'jpeg': 'Joint Photographic Experts Group', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format'}

matplotlib 入門之The Lifecycle of a plot