天天看點

【DataWhale資料可視化學習】布局格式定方圓子圖子圖上的方法作業

DataWhale學習資源:http://datawhale.club/t/topic/542

布局格式定方圓

  • 子圖
    • 使用plt.subplots繪制均勻狀态下的子圖
    • 使用GridSpec繪制非均勻子圖
    • 子圖擴充
      • 實作非均勻子圖合并以及跨圖
      • 均勻子圖的極坐标
  • 子圖上的方法
  • 作業
    • 墨爾本的溫度情況
    • 畫出資料的散點圖和邊際分布
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用來正常顯示中文标簽
plt.rcParams['axes.unicoide_minus'] = False #用來正常顯示負号
           

子圖

使用plt.subplots繪制均勻狀态下的子圖

  • 傳回元素分别是畫布和子圖構成的清單,第一個數字為行,第二資料為列
  • figsize參數可以指定整個畫布的大小
  • sharex和sharey分别表示是否共享橫軸和縱軸的刻度
  • tight_layout函數可以調節子圖的相對大小使字元不會重疊
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用來正常顯示中文标簽
plt.rcParams['axes.unicode_minus'] = False #用來正常顯示負号

fig, axs = plt.subplots(2, 5, figsize = (10, 4), sharex=True, sharey= True)
fig.suptitle('樣例1', size= 20)

for i in range(2):
    for j in range(5):
        axs[i][j].scatter(np.random.randn(10), np.random.randn(10))
        axs[i][j].set_title('第%d行,第%d列' % (i+1, j+1))
        axs[i][j].set_xlim(-5,5)
        axs[i][j].set_xlim(-5,5)
        if i == 1: axs[i][j].set_xlabel('橫坐标')
        if j == 1: axs[i][j].set_ylabel('縱坐标')

fig.tight_layout( ) #tight_layout會自動調整子圖參數,使之填充整個圖像區域。

plt.show( )
           
【DataWhale資料可視化學習】布局格式定方圓子圖子圖上的方法作業

使用GridSpec繪制非均勻子圖

非均勻包含兩層含義:

  • 圖的比例大小不同但沒有跨行或跨列
  • 圖為跨列或者跨行的狀态

利用 add_gridspec 可以指定相對寬度比例 width_ratios 和相對高度比例參數 height_ratios。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用來正常顯示中文标簽
plt.rcParams['axes.unicode_minus'] = False #用來正常顯示負号

fig = plt.figure(figsize=(10, 4))
spec = fig.add_gridspec(nrows= 2, ncols=5, width_ratios=[1,2,3,4,5], height_ratios=[1,3])
fig.suptitle('樣式2',size= 20)
for i in range(2):
    for j in range(5):
        ax = fig.add_subplot(spec[i, j]) #自定義大小
        ax.scatter(np.random.randn(10), np.random.randn(10))
        ax.set_title('第%d行,第%d列' % (i + 1, j + 1))
        if i == 1: ax.set_xlabel('橫坐标')
        if j == 0: ax.set_ylabel('縱坐标')

fig.tight_layout()

plt.show()
           
【DataWhale資料可視化學習】布局格式定方圓子圖子圖上的方法作業

子圖擴充

實作非均勻子圖合并以及跨圖

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用來正常顯示中文标簽
plt.rcParams['axes.unicode_minus'] = False #用來正常顯示負号

fig = plt.figure(figsize=(10, 4))
spec = fig.add_gridspec(nrows=2, ncols=6, width_ratios=[2,2.5,3,1,1.5,2], height_ratios=[1,2])
fig.suptitle('樣例3', size=20)
# sub1
ax = fig.add_subplot(spec[0, :3])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub2
ax = fig.add_subplot(spec[0, 3:5])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub3
ax = fig.add_subplot(spec[:, 5])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub4
ax = fig.add_subplot(spec[1, 0])
ax.scatter(np.random.randn(10), np.random.randn(10))
# sub5
ax = fig.add_subplot(spec[1, 1:5])
ax.scatter(np.random.randn(10), np.random.randn(10))
fig.tight_layout()

plt.show()
           
【DataWhale資料可視化學習】布局格式定方圓子圖子圖上的方法作業

均勻子圖的極坐标

繪制均勻子圖的極坐标時,是plt.subplot()。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用來正常顯示中文标簽
plt.rcParams['axes.unicode_minus'] = False #用來正常顯示負号

N = 150
r = 2 * np.random.rand(N)
theta = 2 * np.pi * np.random.rand(N)
area = 200 * r**2
colors = theta


plt.subplot(projection='polar')   # 要用subplot
plt.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75)
# cmap: 配色方案
# c:color
# s: scale
# alpha:透明度

plt.show()
           
【DataWhale資料可視化學習】布局格式定方圓子圖子圖上的方法作業

顔色圖表:

【DataWhale資料可視化學習】布局格式定方圓子圖子圖上的方法作業

子圖上的方法

在ax對象上定義了和plt類似的圖形繪制函數,常用的有:plot、hist、scatter、bar、barh、pie。

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用來正常顯示中文标簽
plt.rcParams['axes.unicode_minus'] = False #用來正常顯示負号

fig, ax = plt.subplots(figsize=(4, 3))
ax.plot([1,2],[2,1])

plt.show()
           
【DataWhale資料可視化學習】布局格式定方圓子圖子圖上的方法作業
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用來正常顯示中文标簽
plt.rcParams['axes.unicode_minus'] = False #用來正常顯示負号

fig, ax = plt.subplots(figsize=(4, 3))
ax.hist(np.random.randn(1000))

plt.show()
           
【DataWhale資料可視化學習】布局格式定方圓子圖子圖上的方法作業

常用直線的畫法為:axhline、axvline、axline(水準、垂直、任意方向)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用來正常顯示中文标簽
plt.rcParams['axes.unicode_minus'] = False #用來正常顯示負号

fig, ax = plt.subplots(figsize=(4,3))
ax.axhline(0.5,0.2,0.8)
ax.axvline(0.5,0.2,0.8)
ax.axline([0.3,0.3],[0.7,0.7])

plt.show()
           
【DataWhale資料可視化學習】布局格式定方圓子圖子圖上的方法作業

使用grid可以加灰色網絡。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用來正常顯示中文标簽
plt.rcParams['axes.unicode_minus'] = False #用來正常顯示負号

fig, ax = plt.subplots(figsize=(4,3))
ax.grid(True)

plt.show()
           
【DataWhale資料可視化學習】布局格式定方圓子圖子圖上的方法作業

使用 set_xscale, set_title, set_xlabel 分别可以設定坐标軸的規度(指對數坐标等)、标題、軸名

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用來正常顯示中文标簽
plt.rcParams['axes.unicode_minus'] = False #用來正常顯示負号

fig, axs = plt.subplots(1, 2, figsize=(10, 4))
fig.suptitle('大标題', size=20)
for j in range(2):
    axs[j].plot(list('abcd'), [10**i for i in range(4)])
    if j==0:
        axs[j].set_yscale('log')
        axs[j].set_title('子标題1')
        axs[j].set_ylabel('對數坐标')
    else:
        axs[j].set_title('子标題1')
        axs[j].set_ylabel('普通坐标')
fig.tight_layout()

plt.show()
           
【DataWhale資料可視化學習】布局格式定方圓子圖子圖上的方法作業

legend, annotate, arrow, text 對象也可以進行相應的繪制

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用來正常顯示中文标簽
plt.rcParams['axes.unicode_minus'] = False #用來正常顯示負号

fig, ax = plt.subplots()
ax.arrow(0, 0, 1, 1, head_width=0.03, head_length=0.05, facecolor='red', edgecolor='blue')
ax.text(x=0, y=0,s='這是一段文字', fontsize=16, rotation=70, rotation_mode='anchor', color='green')
ax.annotate('這是中點', xy=(0.5, 0.5), xytext=(0.8, 0.2), arrowprops=dict(facecolor='yellow', edgecolor='black'), fontsize=16)

plt.show()
           
【DataWhale資料可視化學習】布局格式定方圓子圖子圖上的方法作業
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用來正常顯示中文标簽
plt.rcParams['axes.unicode_minus'] = False #用來正常顯示負号

fig, ax = plt.subplots()
ax.plot([1,2],[2,1],label="line1")
ax.plot([1,1],[1,2],label="line1")
ax.legend(loc=1)

plt.show()
           
【DataWhale資料可視化學習】布局格式定方圓子圖子圖上的方法作業

圖例中的Loc參數如下:

【DataWhale資料可視化學習】布局格式定方圓子圖子圖上的方法作業

作業

墨爾本的溫度情況

fig,axs = plt.subplots(2,5, figsize=(12,4), sharex=True, sharey=True)
fig.suptitle("墨爾本1981年至1990年月溫度曲線", size=20)
for i in range(2):
    for j in range(5):
        axs[i][j].plot(range(1,13), ex1.iloc[(i*5+j):(i*5+j+12),1], marker=".")
        axs[i][j].set_title(str(1981+i*5+j)+"年")
        axs[i][j].set_xticks(range(1,13))
        axs[i][j].set_ylim(5,20)
        if j == 0:
            axs[i][j].set_ylabel("氣溫")
            
fig.tight_layout()

plt.show() 
           

畫出資料的散點圖和邊際分布

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用來正常顯示中文标簽
plt.rcParams['axes.unicode_minus'] = False #用來正常顯示負号

data = np.random.randn(2, 150)

fig = plt.figure(figsize=(8,8))
spec = fig.add_gridspec(nrows=2, ncols=2, width_ratios=[4,1], height_ratios=[1,4]) 

ax1 = fig.add_subplot(spec[1,0])
ax1.scatter(data[0],data[1])
ax1.grid(True)

ax2 = fig.add_subplot(spec[0,0],sharex=ax1)
ax2.hist(data[0], rwidth=5)
ax2.axis('off')
ax2.spines['top'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax2.spines['bottom'].set_visible(False)
ax2.spines['left'].set_visible(False)

ax3 = fig.add_subplot(spec[1,1],sharey=ax1)
ax3.hist(data[1], orientation='horizontal')
ax3.axis('off')
ax3.spines['top'].set_visible(False)
ax3.spines['right'].set_visible(False)
ax3.spines['bottom'].set_visible(False)
ax3.spines['left'].set_visible(False)
fig.tight_layout()

plt.show( )