前文的兩個案例雖用的都是虛擬資料集,但都有一定的針對性,案例 水果分類(香蕉、蘋果大戰) 中,討論了一個分類問題,并對散點圖、直方圖、箱線圖和等比例子圖的應用做了探討;案例 多元線性回歸 中,討論了一個回歸問題,并對散點圖能最大限度可視化資料的維度做了探討;以上案例涉及演算法的部分,如有難度,可自行忽略,因為本系列主要是針對可視化的,案例的目的是為了賦予一個場景,方便對可視化內容的直觀理解,
本文通過復現1張學術論文圖及3張商業周刊圖,加深對面積圖、折線圖、填充圖等繪圖物件及不等比例子圖、柵格子圖合并內容的理解,
涉及到的繪圖物件傳送門:
折線圖、面積圖、填充圖
涉及到的子圖內容傳送門:
不等比例柵格子圖
子圖物件(坐標軸、刻度、軸標題)設定
本文的運行環境為 jupyter notebook
python版本為3.7
本文所用到的庫包括
%matplotlib inline
from matplotlib.ticker import AutoMinorLocator
from matplotlib.gridspec import GridSpec
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
復現圖表簡介
案例一來源于一篇學術論文:
參考文獻
PRABHU T S, FLORIAN M, THIJS V, et al. Optimizer benchmarking needs to account for hyperparameter tuning[J]. arXiv Preprint arXiv, 2019.
該論文研究了超引數優化資源投入影響優化器的性能,作者展示了各優化器下,超引數優化資源投入與找到優化器超引數配置概率的關系,通過圖表可以發現,投入越高,調優更多的超引數就越有用,

案例二、三、四均來源于《圖表之道》列舉的商業周刊的典型圖表,劉萬祥老師通過Excel單元格和圖物件的巧妙組合,復現了以下3張圖,因matplotlib沒有單元格,因此涉及到的部分采用不等比例的柵格子圖進行行高和列寬地調節,達到了相同的效果,

以下繪圖內容如在手機端閱讀,或許會因長寬比例縮放問題造成比例不協調,還望多理解
案例一
構造資料集
因我們無法獲得論文中的具體資料,因此仍然采用人工構造的方法進行資料生成,觀察原論文的資料變化趨勢,類似sigmoid函式,因此采用sigmoid函式和正太分布的噪音進行資料集的構造,
matplotlib非常適用于學術論文圖的繪制,但即使如此,預設狀態繪制的圖仍然是不那么美觀的,需要不斷地修飾以獲得一定的美感,
x = np.linspace(0, 64, 65)
def sig_array(start, end, size):
z = np.linspace(0, size, size)
sig = 1/(1+np.exp(-1*z)) # 0.5-1
sigA = (sig-sig.min())/(sig.max()-sig.min()) # 0-1
sigA = sigA*(end-start)+start # start-end
return sigA
noise = np.append(np.random.normal(size=64)/300, [0.0])
y1 = sig_array(0.4, 0.58, 65)+noise
y2 = sig_array(0.2, 0.17, 65)+noise
y3 = sig_array(0.2, 0.13, 65)+noise
y4 = 1-(y1+y2+y3)
ys = [y1, y2, y3, y4]
y_stack = y1
for i, y in enumerate(ys):
if i > 0:
y_stack += y
plt.plot(x, y_stack)

以下程序分步地演示了繪制目標圖的步驟:
繪制面積圖
########################前序代碼省略###############################
fig=plt.figure(figsize=(9,5.5))
ax=fig.add_subplot(111)
span=1.02 # 為右側輔助線預留空間
colors=['#99C8DE','#006EA8','#AADA86','#2C9633']
ax.stackplot(x,y1,y2,y3,y4,colors=colors,edgecolor='white',lw=2.5)
ax.set_xlim((0,64*span))
ax.set_ylim((0,1))

繪制右側輔助線
右側輔助線共分為四段,有三個不連續部分,通過**plt.axvline(ax.axvline)**介面實作分段線地繪制,
########################前序代碼省略###############################
blank_white = 0.015
ymins = np.array([0, 0.58+blank_white, 0.58+0.17 +
blank_white, 0.58+0.17+0.13+blank_white])
ymaxs = np.array([0.58-blank_white, 0.58+0.17-blank_white,
0.58+0.17+0.13-blank_white, 1])
line_x_pos = 63.6*span
for ymin, ymax in zip(ymins, ymaxs):
ax.axvline(x=line_x_pos, ymin=ymin, ymax=ymax, lw=4, c='gray')

繪制文本
########################前序代碼省略###############################
poss = np.array([0.58, 0.17, 0.13, 0.12])
optims = [
'Adam (only l.r. tuned)',
'Adam (all params. tuned)',
'SGD (tuned l.r., fixed mom. and w.d.)',
'SGD (l.r. schedule tuned, fixed mom. and w.d.)'
]
fmt = ' %.0f%%'
xmax = 64*span # span=1.02
fontdict = {'family': 'Times New Roman', 'size': 18}
for i, pos in enumerate(poss):
if i == 0:
ax.text(x=xmax, y=0.5*pos, s=fmt % (pos*100),
ha='left', c='gray', va='center', **fontdict)
ax.text(x=xmax-2, y=0.5*pos,
s=optims[i], ha='right', va='center', **fontdict)
else:
ax.text(x=xmax, y=(0.5*pos+poss[:i].sum()), s=fmt %
(pos*100), ha='left', c='gray', va='center', **fontdict)
ax.text(x=xmax-2, y=(0.5*pos+poss[:i].sum()),
s=optims[i], ha='right', va='center', **fontdict)

設定坐標軸顯示及位置
原圖中,x,y軸并不是交于原點的,此處通過ax.spines[‘left’].set_position介面對其位置進行設定,
########################前序代碼省略###############################
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_position(('axes',-0.014)) # axis offset the ax
ax.spines['bottom'].set_position(('axes',-0.02))

設定軸標題
########################前序代碼省略###############################
label_fontdict={'family':'Times New Roman','size':22}
ax.set_xlabel('Budget for hyperparameter optimization (# models trained)',**label_fontdict)
ax.set_ylabel('Probability of being the best',**label_fontdict)

設定刻度
########################前序代碼省略###############################
ax.tick_params(pad=10)
ax.set_xticks(np.arange(10,70,10))
for label in ax.xaxis.get_ticklabels()+ax.yaxis.get_ticklabels():
label.set_fontfamily('Times New Roman')
label.set_fontsize(18)
for line in ax.xaxis.get_ticklines() +ax.yaxis.get_ticklines() :
line.set_markersize(8)

案例二
目標圖

觀察原圖后,考慮按以下方案進行該圖繪制,將圖分為上中下、左中右(分三列的目的是使y坐標軸標簽在圖內,否則會偏離至圖外)六個部分柵格,整體分為上中下三個主要繪圖區域,從而完成繪圖,
繪制柵格
fig = plt.figure(figsize=(5, 7), frameon=True)
nrows, ncols = 3, 3
gs = GridSpec(nrows=nrows, ncols=ncols, hspace=0.3, width_ratios=[
1.5, 15, 0.5], height_ratios=[1.5, 7, 1])
for row in range(nrows):
for col in range(ncols):
ax = fig.add_subplot(gs[row, col])
ax.set_xticks([])
ax.set_yticks([])
ax.text(0.5, 0.5, 'ax%d,%d' % (row, col), va='center',
ha='center', transform=ax.transAxes)

繪制標題行
fig = plt.figure(figsize=(5, 7), facecolor='#D7D7D7', frameon=True)
gs = GridSpec(nrows=3, ncols=3, hspace=0.3, width_ratios=[
1.5, 15, 0.5], height_ratios=[1.5, 7, 1])
# ax0
ax0 = fig.add_subplot(gs[0, :], facecolor='black')
ax0.set_xticks([])
ax0.set_yticks([])
ax0.text(0, 0.9, 'WHY FACTORIES WILL\nSTAY BUSY', c='white', transform=ax0.transAxes,
va='top', ha='left',
fontdict={'size': 19}
)

繪制主體圖
########################前序代碼省略###############################
# ax1
ax1 = fig.add_subplot(gs[1:-1, 1:-1], facecolor='#D7D7D7')
x1 = np.linspace(0, 6, 7)
y11 = [3, -5, 2, 1.5, 2.6, 1.5, 1.8]
y12 = [2, 10, -7, -6, 3.5, 3, 15]
ax1.plot(x1, y11, c='#255D8E', lw=6,
label='MANUFACTURING OUT PUT\n(APR.MAY AVG)')
ax1.plot(x1, y12, c='#D30D15', lw=6, label='UNFILLED ORDERS\n(APR.)')
ax1.set_xlim((0, 6))
ax1.set_ylim((-10, 20))

主體圖坐標軸刻度
########################前序代碼省略###############################
plt.xticks(ticks=x1, labels=['%02d' % i for i in x1])
plt.yticks(ticks=np.linspace(-10, 20, 7))
ax1.xaxis.set_minor_locator(AutoMinorLocator(n=4))

主體圖網格線、標題、圖例
########################前序代碼省略###############################
# set grid
ax1.grid(b=True, which='both')
# set title
ax1.set_title('PERCENT CHANGE FROM A YEAR AGO', loc='left', fontsize=13.5)
# set legend
ax1.legend(handlelength=1, handleheight=1, frameon=False, fontsize=13, loc=2)

主體圖背景填充
########################前序代碼省略###############################
ax1.axhspan(ymin=-5, ymax=0, color='#E7E7E6')
ax1.axhspan(ymin=5, ymax=10, color='#E7E7E6')
ax1.axhspan(ymin=15, ymax=20, color='#E7E7E6')

繪制圖注行
########################前序代碼省略###############################
# ax2
ax2 = fig.add_subplot(gs[-1, 1:-1], frameon=False,)
ax2.set_xticks([])
ax2.set_yticks([])
ax2.set_xlim(0, 1)
ax2.text(-0.09, 0.9, 'Data:Federal Research. U.S.Centry Business\nGlobal investigate inc.', transform=ax2.transAxes,
va='top', ha='left',
fontdict={'size': 11.5}
)
plt.subplots_adjust(left=0, right=1, bottom=0.02,
top=0.98, wspace=0, hspace=0)
plt.tight_layout(pad=0)

案例三
目標圖

繪制柵格
fig = plt.figure(figsize=(4, 6), facecolor='#FFFBFF', frameon=True)
nrows, ncols = 3, 3
gs = GridSpec(nrows=3, ncols=3, left=0, right=1, bottom=0, top=1,
hspace=0.1, height_ratios=[1.4, 10, 2], width_ratios=[1, 15, 1])
for row in range(nrows):
for col in range(ncols):
ax = fig.add_subplot(gs[row, col])
ax.set_xticks([])
ax.set_yticks([])
ax.text(0.5, 0.5, '%d,%d' % (row, col), va='center', fontsize=8,
ha='center', transform=ax.transAxes)

繪制標題行
fig = plt.figure(figsize=(4, 6), facecolor='#FFFBFF', frameon=True)
gs = GridSpec(nrows=3, ncols=3, left=0, right=1, bottom=0, top=1,
hspace=0.1, height_ratios=[1.4, 10, 2], width_ratios=[1, 15, 1])
# ## ax0
ax0 = fig.add_subplot(gs[0, :], frameon=False)
ax0.set_xticks([])
ax0.set_yticks([])
ax0.text(0, 0.9, 'Red hot', c='black', transform=ax0.transAxes,
va='top', ha='left',
fontdict={'size': 19}
)
ax0.text(0, 0.4, 'Venetian\'s', c='black', transform=ax0.transAxes,
va='top', ha='left',
fontdict={'size': 15}
)

繪制主體圖
########################前序代碼省略###############################
ax = fig.add_subplot(gs[1:-1, 1:-1], frameon=False)
ax.spines['left'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
x = range(10)
barline = [0.2, -5, 5, 3, -10, -12, 20, 10, 10, 8]
ax.plot(x, barline, c='#719CB5', lw=4)
ax.set_ylim((-20, 30))
ax.grid(axis='y', lw=4, color='grey')
ax.axhline(y=0, xmin=0, xmax=0.5, lw=4, color='#EFA38D')

調整坐標軸刻度標簽
原圖中y軸刻度標簽的- * 兩個標識,通過次坐標進行位置和標簽的設定
########################前序代碼省略###############################
ax.set_yticks([-20, -10, 0, 10, 20])
ax.set_yticks(ticks=[-5, 5], minor=True)
ax.yaxis.set_ticklabels(['-', '*'], minor=True, fontsize=20)
ax.tick_params(axis='y', width=0)
plt.xticks(ticks=x, labels=['1998', '', '2000',

雙y坐標
在之前的繪圖物件中,為涉及到雙y坐標,但這個相對簡單,只需要通過ax.twinx()介面生成一個次坐標子圖twax即可對該子圖進行繪圖物件和子圖物件的繪制和設定,用法與ax大致相同,
########################前序代碼省略###############################
tw_bar = [22, 20, 22, 25, 19, 18, 22, 27, 40, 52]
tw_line = [22, 21, 28, 26, 29, 50, 70, 75, 60, 100]
twax = ax.twinx()
twax.bar(x=x, height=tw_bar, color='#EFA38D')
twax.plot(x, tw_line, c='#762315', lw=4)
twax.set_ylim((0, 125))
twax.grid(b=False)

圖例和坐標軸設定
########################前序代碼省略###############################
ax_legend_h = ax.get_legend_handles_labels()[0]
ax.legend(ax_legend_h, labels=['GDP\n with asian'], loc=2, frameon=False)
twax_legend_h = twax.get_legend_handles_labels()[0]
twax.legend(twax_legend_h, labels=[
'price', 'incoms'], loc=1, markerfirst=False, frameon=False)
twax.spines['left'].set_visible(False)
twax.spines['right'].set_visible(False)
twax.spines['top'].set_visible(False)
twax.set_yticks([0, 25, 50, 75, 100])
twax.tick_params(axis='y', width=0)

繪制圖注行
########################前序代碼省略###############################
ax3 = fig.add_subplot(gs[-1, :], frameon=False)
ax3.set_xticks([])
ax3.set_yticks([])
ax3.text(0.3, 0.9, '*West Texcas Internations #ffdfd', transform=ax3.transAxes,
va='top', ha='left',
fontdict={'size': 11.5}
)
ax3.text(0, 0.5, 'Data:Federal Research. U.S.Centry Business\nGlobal investigate inc.', transform=ax3.transAxes,
va='top', ha='left',
fontdict={'size': 11.5}
)

案例四
目標圖

本案例的難度在于背景的漸變色填充,在填充圖部分并沒有介紹過漸變色填充的方法,實際上,填充圖也沒有漸變色填充的介面,漸變色是通過技巧設定而成,
構造資料集
np.random.seed(3)
x = np.linspace(0, 7, 100)
y = [20]
for i in range(99):
y.append(y[-1]+np.random.uniform(-0.5, 0.5))
y = np.array(y)
plt.plot(x, y, lw=4, c='black')

繪制背景圖
背景圖是產生影像漸變效果的主要原因,通過**plt.imshow(ax.imshow)**介面實作,
np.random.seed(3)
x = np.linspace(0, 7, 100)
y = [20]
for i in range(99):
y.append(y[-1]+np.random.uniform(-0.5, 0.5))
y = np.array(y)
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, frameon=True)
# 繪制趨勢線
ax.plot(x, y, lw=4, c='black')
xlim = xmin, xmax = x.min(), x.max()
ylim = ymin, ymax = y.min(), y.max()
# 將整張圖用漸變色背景進行填充
ax.imshow(X=[[100, 100], [0, 0]],
cmap=plt.cm.Blues,
norm=None,
extent=(xmin, xmax, ymin, ymax),
aspect='auto',
interpolation='bicubic',
vmin=1,
vmax=120,)

將上部用純色填充
########################前序代碼省略###############################
ax.fill_between( x=x,y1=y,y2=ymax,color='#FFFBFF')

調整x坐標軸
########################前序代碼省略###############################
ax.set_xticks(np.linspace(0, 7, 8))
blank = " "*6
ax.xaxis.set_ticklabels(
ticklabels=['',
blank+'Sep',
blank+'Oct',
blank+'',
blank+'Dec',
blank+'Jan',
'', ''],)
ax.tick_params(axis='x', pad=-20 # 通過pad將數值調整到坐標軸上方
, labelsize=20, direction='in', right=True, left=False, labelright=True, labelleft=False)

調整y坐標軸
########################前序代碼省略###############################
ax.set_yticks([16.5, 18.5, 19.4])
ax.tick_params(axis='y', pad=-50, labelsize=20, width=3, direction='in',
length=50, right=True, left=False, labelright=True, labelleft=False)
ax.yaxis.set_ticklabels(
ticklabels=[
"%.1f\n" % 16.5,
"%.1f\n" % 18.5,
"%.1f\n" % 19.4,
],)

網格線、標題
########################前序代碼省略###############################
ax.grid(lw=2, color='gray', alpha=0.3)
ax.set_xlim((0, 8))
ax.set_title('GDP CHANGE VALUE PER MONTH\nunit:% per month',
loc='left', fontdict={'size': 22})
plt.subplots_adjust(left=0.02, right=0.98, bottom=0.05,
top=0.85, wspace=0, hspace=0)

總結
從上述案例可以看出,繪制一張高顏值的圖表需要修飾和調整的內容是很多的,是對繪圖物件及圖物件的綜合應用,
案例一繪圖程序

案例二繪圖程序

案例三繪圖程序

案例四繪圖程序
至此,第一階段的案例部分基本結束,
希望對你有所幫助和啟發!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/117615.html
標籤:其他
上一篇:一張學習規劃圖學透自動化測驗
