重新使用 python 庫 matplotlib.pyplot 創建的條形圖我有三個問題:
- 如何格式化網格,使垂直網格線不會穿過條形但位于條形之間?
- 如何始終將值標簽放置在欄的頂部?
- 如何控制第一條左側大邊距的大小?
- 顯示為條形標簽的值是 ysizes_base 和 ysizes_add 之和;我只期望 ysizes_add 的值。我該如何做到這一點?
代碼讀取
import math
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
ysizes_base = [0, 2850, 3403, 3803, 4043, 4273, 4499, 4699, 4848, 4958, 5042, 5122, 5195, 5265, 5328, 5373, 5408, 5433, 5458, 5481, 5491, 5486, 5481, 5475, 5465, 5455, 5445, 5435, 5425, 5408, 5388, 5367, 5342, 5312, 5273, 5233, 5193, 5152, 5102, 5047, 4992, 4927, 4862, 4796, 4696, 4596, 4486, 4361, 4206, 4036]
ysizes_add = [2850, 553, 400, 240, 230, 226, 200, 149, 110, 84, 80, 73, 70, 63, 45, 35, 25, 25, 23, 10, -5, -5, -6, -10, -10, -10, -10, -10, -17, -20, -21, -25, -30, -39, -40, -40, -41, -50, -55, -55, -65, -65, -66, -100, -100, -110, -125, -155, -170, -175]
short_texts = ['Rx', 'Ca', 'AP', 'Br', 'RM', 'VCA', 'Tu', 'He', 'Cha', 'Cho', 'PP', 'VC', 'BP', 'Gu', 'Di', 'FPJ', 'Hu', 'RD', 'Ze', 'AL', 'Or', 'ML', 'HW', 'IWC', 'FM', 'GO', 'BR', 'Mo', 'OP', 'Ce', 'BM', 'Ha', 'FC', 'Pi', 'UN', 'CFB', 'JLC', 'Mi', 'Mo', 'CKW', 'Vi', 'Ti', 'Sw', 'Bu', 'Ra', 'Lo', 'Br', 'Om', 'Ti', 'TH']
fig, ax = plt.subplots(1,1, figsize=(12, 12 / math.sqrt(2.0)))
ax.tick_params(axis='both', which='both', labelsize='small', colors='gray', labelrotation=90.0)
ax.set_ylim([0.0, 1.1 * max(ysizes_base)]) # w/o 1.1 the labels do not fit
ax.grid(visible=True)
ax.set_xticks(range(len(ysizes_base)), labels=short_texts)
abx = ax.bar(range(len(ysizes_base)), height=ysizes_add, bottom=ysizes_base, color='blue', align='center')
ax.bar_label(abx, label_type='edge', padding=5.0, rotation=90.0, fontsize=6, color='gray')
plt.show()
Re (1) 我也嘗試過abx = ax.bar(..., align='edge'),但這會將條形發送到左邊緣(如預期的那樣)。
Re (2) 我檢查過label_type='center',但它只支持'edge', 'center'.

uj5u.com熱心網友回復:
下面的代碼進行了以下更改:
- 引入 numpy 以啟用
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/512060.html
