一行代碼讓matplotlib圖表變高大上

導讀:懶人數(shù)據(jù)可視化必備。

02 利用dufte自動改造matplotlib圖表
1. 主題設置
# 局部主題設置
with plt.style.context(主題):
# 繪圖代碼
...
import dufte
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager
# 注冊本地思源宋體
fontproperties = font_manager.FontProperties(fname='NotoSerifSC-Regular.otf')折線圖
# 折線圖示例
with plt.style.context(dufte.style):
x = range(100)
y = np.random.standard_normal(100).cumsum()
fig, ax = plt.subplots(figsize=(10, 5), facecolor='white', edgecolor='white')
ax.plot(x, y, linestyle='-.', color='#607d8b')
ax.set_xlabel('x軸示例', fontproperties=fontproperties, fontsize=16)
ax.set_ylabel('y軸示例', fontproperties=fontproperties, fontsize=16)
ax.set_title('折線圖示例', fontproperties=fontproperties, fontsize=20)
fig.savefig('圖2.png', dpi=300, bbox_inches='tight')
柱狀圖
# 柱狀圖示例
with plt.style.context(dufte.style):
x = range(25)
y = np.random.standard_normal(25)
fig, ax = plt.subplots(figsize=(10, 5), facecolor='white', edgecolor='white')
ax.bar(x, y)
ax.set_xlabel('x軸示例', fontproperties=fontproperties, fontsize=16)
ax.set_ylabel('y軸示例', fontproperties=fontproperties, fontsize=16)
ax.set_title('柱狀圖示例', fontproperties=fontproperties, fontsize=20)
fig.savefig('圖3.png', dpi=300, bbox_inches='tight')
2. 自動圖例美化
# 折線圖示例
with plt.style.context(dufte.style):
x = range(100)
y1 = np.random.randint(-5, 6, 100).cumsum()
y2 = np.random.randint(-5, 10, 100).cumsum()
y3 = np.random.randint(-5, 6, 100).cumsum()
fig, ax = plt.subplots(figsize=(10, 5), facecolor='white', edgecolor='white')
ax.plot(x, y1, linestyle='dotted', label='Series 1')
ax.plot(x, y2, linestyle='dashed', label='Series 2')
ax.plot(x, y3, linestyle='dashdot', label='Series 3')
ax.set_xlabel('x軸示例', fontproperties=fontproperties, fontsize=16)
ax.set_ylabel('y軸示例', fontproperties=fontproperties, fontsize=16)
dufte.legend()
ax.set_title('dufte.legend()示例', fontproperties=fontproperties, fontsize=20)
fig.savefig('圖4.png', dpi=300, bbox_inches='tight')
3. 柱狀圖自動標注
# 柱狀圖示例
with plt.style.context(dufte.style):
x = range(15)
y = np.random.randint(5, 15, 15)
fig, ax = plt.subplots(figsize=(10, 5), facecolor='white', edgecolor='white')
ax.bar(x, y)
ax.set_xticks(x)
ax.set_xticklabels([f'項目{i}' for i in x], fontproperties=fontproperties, fontsize=10)
dufte.show_bar_values()
ax.set_xlabel('x軸示例', fontproperties=fontproperties, fontsize=16)
ax.set_ylabel('y軸示例', fontproperties=fontproperties, fontsize=16)
ax.set_title('柱狀圖示例', fontproperties=fontproperties, fontsize=20)
fig.savefig('圖5.png', dpi=300, bbox_inches='tight')


評論
圖片
表情
