背景
最近使用python matplotlib繪制柱狀圖時,想要更清晰地查看每一項占總數的百分比,在搜索后發現matplotlib.pyplot.bar
方法并沒有提供這個參數,于是自己嘗試實現了這個功能。
實現方法
實現方法很簡單,利用plt.text
方法在柱狀圖的合適位置添加計算后的百分比數值即可,添加的位置這里選擇了柱狀圖頂端的合適位置,更改plt.text(x, y + y_max / 20, str(round(percentage[x], 2)), ha='center')
這行代碼里的參數也可很容易實現在柱狀圖的中間等位置進行繪制添加。
詳細代碼如下:
import matplotlib.pyplot as plt
def bar_with_percentage_plot(x_list, y_list):
# 繪圖參數, 第一個參數是x軸的數據, 第二個參數是y軸的數據,
# 第三個參數是柱子的大小, 默認值是1(值在0到1之間), color是柱子的顏色, alpha是柱子的透明度
plt.bar(range(len(x_list)), y_list, 0.4, color='r', alpha=0.8)
# 添加軸標簽
plt.ylabel('y軸')
# 標題
plt.title('柱狀圖添加百分比')
# 添加刻度標簽
plt.xticks(range(len(x_list)), x_list)
# 設置Y軸的刻度范圍
y_max = max(y_list) + max(y_list) / 6
plt.ylim([0, y_max])
y_sum = sum(y_list)
percentage = [x / y_sum for x in y_list]
# 為每個條形圖添加數值標簽
for x, y in enumerate(y_list):
plt.text(x, y + y_max / 20, str(round(percentage[x], 2)), ha='center')
# 顯示圖形
plt.show()
if __name__ == '__main__':
x_list = ['A', 'B', 'C', 'D']
y_list = [110, 30, 200, 150]
bar_with_percentage_plot(x_list, y_list)
最終顯示效果如下圖所示:
image.png