有什么方法可以将x点放置在堆叠条形图中的每个堆叠条形上方,而不是在x轴下方?需要明确的是,我并不是说将x-tick放在单个堆叠栏中的上方,我的意思是将x-tick放在堆叠起来的bar本身上方。这是我创建情节的方法:
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处放置文本“ site(173)”以及对勾。
供大家参考,我已经张贴图片我当前的代码会产生什么,我想生产什么:电流:https://i.stack.imgur.com/QDlEP.png目标:HTTPS://i.stack .imgur.com / IJJo4.png
这可以通过使用@Evan链接到这个意见,即例如可以实现这一个。重要的一点是autolabel
链接示例中命名的函数。改变值从Y轴的值显示于x轴的值是容易的,替换height
用rect.get_x()
。棘手的一点是将值放在栏的顶部。条形的总高度可以通过将DataFrame中的值相加得出。
heights = df_select.iloc[:,:].sum(axis=1)
然后需要将其传递给自动标签功能,并用作条的高度。可以使用以下方式删除x刻度标签
ax.get_xaxis().set_ticklabels([])
而且,您可以通过将xax.text
的内容sites
用作x位置,并将y位置设置为在轴下方(-0.5或类似值),从而在特定站点的x轴下方添加更多文本。
综上所述,我们得到以下工作示例:
def autolabel(rects, heights):
"""
Attach a text label above each bar displaying its height
Modified for use with a stacked bar chart
"""
for i, rect in enumerate(rects):
x = rect.get_x()
wid = rect.get_width()
height = heights.values[i]
ax.text(x + wid/2., 1.05*height,
'%d' % (int(x) + int((wid/2)+0.5)),
ha='center', va='bottom', rotation=90)
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], width = 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)
rects1 = ax.bar(df_select.index, df_select.iloc[:,i], bottom=bottom, label =
df_select.columns[i], width = 15)
ax.set_xticks(df_select.index)
ax.get_xaxis().set_ticklabels([]) # turn off the x tick labels
plt.legend(loc='best', bbox_to_anchor=(1, 0.5))
heights = df_select.iloc[:, :].sum(axis=1)
autolabel(rects1, heights)
# Select 3 random value to add labels below the x axis. Make sure they are
# within the axis limits
sites = np.random.choice(df_select.index, 3)
for site in sites:
ax.text(site, -0.5,
'site(%s)' % site,
ha='center', va='bottom',fontsize=6)
plt.show()
如下图所示:
注意:由于条形图非常细且散开,并且可以彼此靠近放置,因此有时看起来会很乱,这意味着值可能开始重叠。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句