matplotlib 餅圖+ 柱狀圖的繪製(官方案例)

1. 代碼

import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
import numpy as np

# 創建 figure 圖片, 然後分配子視圖
# make figure and assign axis objects
fig = plt.figure(figsize=(9, 5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
fig.subplots_adjust(wspace=0)

# 繪製餅圖
# pie chart parameters
ratios = [.27, .56, .17]
labels = ['Approve', 'Disapprove', 'Undecided']
explode = [0.1, 0, 0]  # 表示要突出誰
# rotate so that first wedge is split by the x-axis
# startangle 表示餅圖開始的角度, 還是一個角度值
angle = -180 * ratios[0]
ax1.pie(ratios, autopct='%1.1f%%', startangle=angle,
        labels=labels, explode=explode, radius=1.5)  # 更改它的半徑

# 畫了一個柱狀圖, 分析餅塊中的比例
# bar chart parameters
xpos = 0
bottom = 0
ratios = [.33, .54, .07, .06]
width = .2
# colors = [[.1, .3, .5], [.1, .3, .3], [.1, .3, .7], [.1, .3, .9]]
colors = np.random.rand(4, 3)  # 顏色進行隨機的給定

for j in range(len(ratios)):
    height = ratios[j]
    ax2.bar(xpos, height, width, bottom=bottom, color=colors[j])
    ypos = bottom + ax2.patches[j].get_height() / 2
    bottom += height  # bottom是 一直在改變的
    # ax2.text(xpos, ypos, "%d%%" % (ax2.patches[j].get_height() * 100),
    print(ypos)
    ax2.text(xpos, ypos - 0.015, "%d%%" % (ratios[j] * 100),  # ratios就是詳細的比例
             ha='center')

ax2.set_title('Age of approvers')
ax2.legend(('50-65', 'Over 65', '35-49', 'Under 35'))
ax2.axis('off')
ax2.set_xlim(- 2.5 * width, 2.5 * width)  # 設置橫座標的寬度,此時是(-0.5, 0.5)

# 將兩個視圖進行連線,
# use ConnectionPatch to draw lines between the two plots
# get the wedge data
# theta1,theta2 就是角度
theta1, theta2 = ax1.patches[0].theta1, ax1.patches[0].theta2
center, r = ax1.patches[0].center, ax1.patches[0].r
print('---', theta1, theta2, center, r)
# 條形圖的高度
bar_height = sum([item.get_height() for item in ax2.patches])
print('+++', bar_height)

# draw top connecting line  繪製上邊的連線
#   獲取角度從而獲取餅圖上線的位置,
#   這裏加上 center 的原因是 進行突出後, 中心的位置發生了改變
x = r * np.cos(np.pi / 180 * theta2) + center[0]
y = r * np.sin(np.pi / 180 * theta2) + center[1]  # 更改了半徑這裏需要更改
# 連接兩個圖, 這裏指定一下a的
# 這裏xyA就是柱子上線的起始位置, 如果想要往左邊挪, 給定 -width / 2
con = ConnectionPatch(xyA=(-width / 2, bar_height), coordsA=ax2.transData,
                      xyB=(x, y), coordsB=ax1.transData)
con.set_color([0, 0, 0])  # 設置連線的寬度
con.set_linewidth(4)  # 設置連線的顏色
ax2.add_artist(con)

# draw bottom connecting line  繪製下邊的線
x = r * np.cos(np.pi / 180 * theta1) + center[0]
y = r * np.sin(np.pi / 180 * theta1) + center[1]
con = ConnectionPatch(xyA=(-width / 2, 0), coordsA=ax2.transData,
                      xyB=(x, y), coordsB=ax1.transData)
con.set_color([0, 0, 0])
ax2.add_artist(con)
con.set_linewidth(4)

plt.show()

2. 最終效果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章