我正在嘗試使用 matplotlib 向這個堆疊的分組條形圖添加兩層標簽。每個組的每個相應位置的每個條都應具有相同的標簽(即,每組中的第一個條應標記為“1”,每組中的第二個條應標記為“2”,等等)。然后我希望每個組都有第二層標簽。到目前為止,這就是我所擁有的:
width = 0.25
x = np.arange(1, 7)
fig = plt.figure(figsize=(10,6))
ax = plt.axes()
ax.bar(x-0.4, shift1_rbc, width, color='red', tick_label='1')
ax.bar(x-0.1, shift2_rbc, width, color='red')
ax.bar(x 0.2, shift3_rbc, width, color='red')
ax.bar(x-0.4, shift1_plt, width*.7, color='blue')
ax.bar(x-0.1, shift2_plt, width*.7, color='blue')
ax.bar(x 0.2, shift3_plt, width*.7, color='blue')
ax.bar(x-0.4, shift1_ffp, width*.5, color='green')
ax.bar(x-0.1, shift2_ffp, width*.5, color='green')
ax.bar(x 0.2, shift3_ffp, width*.5, color='green')

當我嘗試將“tick_label”引數添加到另一組條形時,它會替換以前的標簽,如下所示:
width = 0.25
x = np.arange(1, 7)
fig = plt.figure(figsize=(10,6))
ax = plt.axes()
ax.bar(x-0.4, shift1_rbc, width, color='red', tick_label='1')
ax.bar(x-0.1, shift2_rbc, width, color='red', tick_label='1')
ax.bar(x 0.2, shift3_rbc, width, color='red')
ax.bar(x-0.4, shift1_plt, width*.7, color='blue')
ax.bar(x-0.1, shift2_plt, width*.7, color='blue')
ax.bar(x 0.2, shift3_plt, width*.7, color='blue')
ax.bar(x-0.4, shift1_ffp, width*.5, color='green')
ax.bar(x-0.1, shift2_ffp, width*.5, color='green')
ax.bar(x 0.2, shift3_ffp, width*.5, color='green')

我感謝任何人可以提供的任何幫助!
uj5u.com熱心網友回復:
一個簡單的解決方案是連接所有 x 值、所有條形高度和所有刻度標簽。然后一口氣畫出來(不需要排序):
import matplotlib.pyplot as plt
import numpy as np
width = 0.25
x = np.arange(1, 7)
fig, ax = plt.subplots(figsize=(10, 6))
tick_labels_1 = ['1'] * len(x)
tick_labels_2 = ['2'] * len(x)
tick_labels_3 = ['3'] * len(x)
shift1_rbc = np.random.uniform(1100, 1200, 6)
shift2_rbc = np.random.uniform(900, 1000, 6)
shift3_rbc = np.random.uniform(1000, 1100, 6)
shift1_plt = np.random.uniform(600, 700, 6)
shift2_plt = np.random.uniform(400, 500, 6)
shift3_plt = np.random.uniform(500, 600, 6)
shift1_ffp = np.random.uniform(250, 300, 6)
shift2_ffp = np.random.uniform(150, 200, 6)
shift3_ffp = np.random.uniform(200, 250, 6)
all_x = np.concatenate([x - 0.4, x - 0.1, x 0.2])
ax.bar(all_x, np.concatenate([shift1_rbc, shift2_rbc, shift3_rbc]), width,
tick_label=tick_labels_1 tick_labels_2 tick_labels_3,
color='crimson', label='red')
ax.bar(all_x, np.concatenate([shift1_plt, shift2_plt, shift3_plt]),
width * .7, color='dodgerblue', label='blue')
ax.bar(all_x, np.concatenate([shift1_ffp, shift2_ffp, shift3_ffp]),
width * .5, color='limegreen', label='green')
ax.margins(x=0.02)
ax.legend(title='Data', bbox_to_anchor=(0.99, 1), loc='upper left')
for spine in ['top', 'right']:
ax.spines[spine].set_visible(False)
ax.set_xticks(x - 0.1001, minor=True)
ax.set_xticklabels(['January', 'February', 'March', 'April', 'May', 'June'], minor=True)
ax.tick_params(axis='x', which='minor', length=0, pad=18)
plt.tight_layout()
plt.show()

PS:要獲得 3 層標簽,可以使用換行符:
tick_labels_1 = ['1\n4\n7'] * len(x)
tick_labels_2 = ['2\n5\n8'] * len(x)
tick_labels_3 = ['3\n6\n9'] * len(x)

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/406540.html
標籤:
