【发布时间】:2018-01-04 21:24:36
【问题描述】:
有没有办法将 x 刻度放在堆叠条形图中每个堆叠条的上方,而不是 x 轴下方?需要明确的是,我并不是说将 x-tick 放在单个堆叠条中的每个单独条上方,我的意思是将 x-tick 放在堆叠条本身上方。以下是我创建情节的方式:
df = pd.DataFrame(np.random.randint(1, 5, size=(3200, 3)))
df.loc[np.random.choice(df.index, size=3190, replace=False), :] = 0
df_select = df[df.sum(axis=1)>1]
fig, ax = plt.subplots()
ax.bar(df_select.index, df_select.iloc[:,0], label = df_select.columns[0], wdith = 15)
if df_select.shape[1] > 1:
for i in range(1, df_select.shape[1]):
bottom = df_select.iloc[:,np.arange(0,i,1)].sum(axis=1)
ax.bar(df_select.index, df_select.iloc[:,i], bottom=bottom, label =
df_select.columns[i], width = 15)
ax.set_xticks(df_select.index)
plt.legend(loc='best', bbox_to_anchor=(1, 0.5))
plt.xticks(rotation=90, fontsize=8) #this puts the x ticks below the x axis
此外,我想在 x 轴的特定点放置一些文本。我将这些网站存储在一个列表中:
sites = [19, 173, 1002] # the number and elements of this list vary
因此,例如,在 x = 173 处,我想在位置 173 处放置文本“站点 (173)”以及一个刻度。
供您参考,我已经发布了我当前代码生成的图像以及我想要生成的图像: 当前:https://i.stack.imgur.com/QDlEP.png 目标:https://i.stack.imgur.com/IJJo4.png
【问题讨论】:
-
是的,但我想把 x val 放在栏的顶部,而不是 y val。我已经尝试使用链接中的代码(调整为放置 x val 而不是 y),但由于它是堆叠图,它似乎不起作用
-
你能发布你更新的代码吗?我无法根据您发布的内容获得合理的情节;假设导入了 np、pd、plt。
-
尝试为 ax.bar() 传递宽度...在某些情况下,这些条似乎太细而无法显示。 width = 15 为我工作
标签: python pandas matplotlib plot figure