繁体   English   中英

Matplotlib条形图仅在非零条形图中显示x点

[英]Matplotlib bar chart show x-ticks only at non-zero bars

我必须制作一个(堆积的)条形图,在x轴上有〜3000个位置。 但是,这些位置中的许多位置都不包含条形图,但仍在x轴上进行了标记,因此很难读取该图。 有什么方法可以只显示现有(堆叠)条的x-ticks吗? 基于x-tick值的条之间的空格是必需的。 如何在matplotlib中解决这个问题? 是否有比堆积条形图更合适的图? 我正在从熊猫交叉表(pd.crosstab())构建图。

链接到图的图像: https : //i.stack.imgur.com/qk99z.png

作为我的数据框外观的示例(感谢gepcel):

import pandas as pd
import numpy as np
N = 3200
df = pd.DataFrame(np.random.randint(1, 5, size=(N, 3)))
df.loc[np.random.choice(df.index, size=3190, replace=False), :] = 0
df_select = df[df.sum(axis=1)>0]

基本上,没有示例,您应该选择总价值(即堆叠价值)大于零的刻度。 然后手动设置xticks和xticklabels。

假设您有一个如下数据框:

import pandas as pd
import numpy as np
N = 3200
df = pd.DataFrame(np.random.randint(1, 5, size=(N, 3)))
df.loc[np.random.choice(df.index, size=3190, replace=False), :] = 0

然后,所选数据应如下所示:

df_select = df[df.sum(axis=1)>0]

然后,您可以绘制堆积的条形图,例如:

# set width=20, the bar is not too thin to show
plt.bar(df_select.index, df_select[0], width=20, label='0')
plt.bar(df_select.index, df_select[1], width=20, label='1',
        bottom=df_select[0])
plt.bar(df_select.index, df_select[2], width=20, label='2',
        bottom=df_select[0]+df_select[1])
# Only show the selected ticks, it'll be a little tricky if
# you want ticklabels to be different than ticks
# And still hard to avoid ticklabels overlapping
plt.xticks(df_select.index)
plt.legend()
plt.show()

结果应该是这样的: 在此处输入图片说明

更新

通过以下方式将文本放在小节顶部很容易:

for n, row in df_select.iterrows():
    plt.text(n, row.sum()+0.2, n, ha='center', rotation=90, va='bottom')

它是计算每个条形图顶部的位置,然后在其中放置文本,并可能添加一些偏移量(例如+0.2 ),并使用rotation=90来控制旋转。 完整代码为:

df_select = df[df.sum(axis=1)>0]
plt.bar(df_select.index, df_select[0], width=20, label='0')
plt.bar(df_select.index, df_select[1], width=20, label='1',
        bottom=df_select[0])
plt.bar(df_select.index, df_select[2], width=20, label='2',
        bottom=df_select[0]+df_select[1])

# Here is the part to put text:
for n, row in df_select.iterrows():
    plt.text(n, row.sum()+0.2, n, ha='center', rotation=90, va='bottom')

plt.xticks(df_select.index)
plt.legend()
plt.show()

结果是:

在此处输入图片说明

这是gepcel答案的一种扭曲,它适用于具有不同列数的数据框:

# in this case I'm creating the dataframe with 3 columns
# but the code is meant to adapt to dataframes with varying column numbers
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])

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])

ax.set_xticks(df_select.index)
plt.legend(loc='best', bbox_to_anchor=(1, 0.5))
plt.xticks(rotation=90, fontsize=8)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM