軟件版本:
0、import
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.patches import ConnectionPatch
1、繪圖
# 使圖表元素中正常顯示中文
mpl.rcParams['font.sans-serif'] = 'SimHei'
# 使坐標軸刻度標簽正常顯示負號
mpl.rcParams['axes.unicode_minus'] = False # -------------------------------- 創建畫布,划分子區 --------------------------------
fig = plt.figure(figsize=(12, 8), facecolor='cornsilk' ) ax1, ax2 = fig.subplots(nrows=1, ncols=2 ) # ------------------------------------- 繪制餅圖 -------------------------------------
sales = [138, 181, 118, 107, 387] labels = ['子', '丑', '寅', '卯', '其他'] #
ax1.pie(x=sales, # 數據
autopct='%1.1f%%', # 鍥形塊的數據標簽格式
startangle=70, # 鍥形塊開始角度
labels=labels, colors=cm.Blues(range(1, 300, 50)), explode=[0, 0, 0, 0, 0.05], # 分裂距離
textprops={'color': 'k', 'fontsize': 16}, ) # ------------------------------------- 繪制條形圖 -------------------------------------
sales = [98, 170, 119] labels = ['甲', '乙', '丙'] colors = ['green', 'red', 'yellow'] xpos = 0 bottom = 0 for j, _ in enumerate(sales): ration = sales[j]/sum(sales) ax2.bar(x=xpos, height=ration, width=0.5, bottom=bottom, color=colors[j] ) ypos = bottom + ax2.patches[j].get_height() / 2 bottom += ration # 通過自增,實現堆積柱形的效果
# 添加數據標簽
ax2.text(x=xpos, # 標簽文本的橫軸坐標
y=ypos, # 豎軸坐標
s='%s, %3.2f%%' % (labels[j], ax2.patches[j].get_height()), # 標簽的文本內容
fontsize=16, ha='center', # horizontal alignment
) ax2.axis('off') # 關閉坐標軸
# 設置刻度范圍
ax2.set_xlim(xmin=-0.6, xmax=1
) # ------------------------------------- 繪制連接線 ------------------------------------- # 獲取鍥形塊的數據
theta1, theta2 = ax1.patches[-1].theta1, ax1.patches[-1].theta2 center, r = ax1.patches[-1].center, ax1.patches[-1].r bar_height = sum([item.get_height() for item in ax2.patches]) # 上連接線
x = r * np.cos(np.pi / 180 * theta2) + center[0] y = np.sin(np.pi / 180 * theta2) + center[1] con1 = ConnectionPatch(xyA=(-width / 2, bar_height), coordsA=ax2.transData, xyB=(x, y), coordsB=ax1.transData ) # 下連接線
x = r * np.cos(np.pi / 180 * theta1) + center[0] y = np.sin(np.pi / 180 * theta1) + center[1] con2 = ConnectionPatch(xyA=(-width / 2, 0), coordsA=ax2.transData, xyB=(x, y), coordsB=ax1.transData ) # 添加連接線
for con in [con1, con2]: con.set_color('gray') ax2.add_artist(con) con.set_linewidth(3) # 調整子區布局
fig.subplots_adjust(wspace=0) # 顯示圖形
plt.show()
圖形: