前言
本文目標在於利用 快速畫出符合自己要求的柱狀圖。
最近在處理某一組成績數據的時候,涉及了柱狀圖的畫法,因此此處進行一下記錄。
加載庫
import matplotlib.pyplot as plt
import matplotlib.font_manager as mfm
from matplotlib import style
style.use('ggplot') # 加載'ggplot'風格
# 加載中文字體
font_path = "/System/Library/Fonts/STHeiti Light.ttc" # 本地字體鏈接
prop = mfm.FontProperties(fname=font_path)
單一柱圖
其中 表示分數在 區間內的人數。
total = [3, 5, 6, 7, 8, 6, 4, 3, 3, 22, 4, 8, 7, 13, 7, 7, 15, 10, 6, 52, 8, 2, 3, 26, 1, 1, 0, 2, 0, 3]
如果直接對於上述數據執行下述代碼,將得到如下結果。
plt.bar(range(len(total)), total)
plt.title('單一柱圖', fontproperties=prop)
plt.savefig("單一柱圖.png", dpi=700, fontproperties=prop)
plt.show()
不難發現,上述結果的效果不好。首先第一點,分數段是 ,而此處顯示的是 後的數值。其次,最後一根柱子沒有數據顯示,但其實應該顯示 的數據,因此我們需要對此進行改進。
自定義橫座標
因此我們選擇自定義橫座標的方式來進行效果改進,具體代碼如下。
x_labels = []
for item in range(0, 300, 10):
x = item + 10
if x == 10:
x_labels.append("{}~{}".format(0, 10))
elif x % 50 == 0:
x_labels.append("{}".format(x))
else:
x_labels.append(None)
x = range(len(total))
plt.bar(x, total)
plt.title('單一柱圖', fontproperties=prop)
plt.xticks(x, x_labels)
plt.savefig("單一柱圖.png", dpi=700, fontproperties=prop)
plt.show()
我們在 個區間中僅選取了一部分進行標註,以及令第一個區間以 的方式進行顯示。
多柱圖
在展示完單一柱圖之後,我們進入多柱同時顯示的代碼內容。首先是數據內容的展示, 表示第 題得分在 範圍內的人數。
A = [[28, 3, 5, 6, 3, 7, 2, 4, 9, 95],
[58, 6, 13, 13, 5, 12, 17, 11, 10, 102],
[60, 22, 21, 41, 11, 5, 1, 2, 3, 4]]
然後我們執行下述代碼即可得到下述多柱圖。
# 生成橫座標
x_labels = []
for item in range(0, 100, 10):
x = item + 10
if x == 10:
x_labels.append("{}~{}".format(0, 10))
else:
x_labels.append("{}".format(x))
# 生成橫座標範圍
x = np.arange(10)
# 生成多柱圖
plt.bar(x + 0.00, A[0], color='orange', width=0.3, label="A")
plt.bar(x + 0.30, A[1], color='royalblue', width=0.3, label="B")
plt.bar(x + 0.60, A[2], color='brown', width=0.3, label="C")
# 圖片名稱
plt.title('多柱圖', fontproperties=prop)
# 橫座標綁定
plt.xticks(x + 0.30, x_labels)
# 生成圖片
plt.legend(loc="best")
plt.savefig("多柱圖.png", dpi=700, fontproperties=prop)
plt.show()
後記
至此,Python 柱狀圖
的基礎操作就介紹完畢了,本文也算是對於上一篇 《一次性掌握所有 Python 畫圖基礎操作》 文章的一個補充,不過仍然還有很多其他類型圖的畫法沒有介紹,感興趣的朋友可以繼續深入研究!
最後祝大家畫圖快樂,在 Python
的畫圖之路上更進一步!💪💪💪