为了账号安全,请及时绑定邮箱和手机立即绑定

如何删除条形图中绘制值为零的条形之间的空格?

如何删除条形图中绘制值为零的条形之间的空格?

陪伴而非守候 2023-09-19 15:27:42
有时,数据集有许多变量,以及一些对它们有贡献的其他“事物”。显示这些不同“事物”对变量的贡献(例如%)可能很有用。然而,有时并非所有“事物”都会对所有变量产生影响。当绘制为条形图时,当特定变量没有“事物”的贡献时,这会导致出现空格。如果“事物”的贡献为零,有没有办法在条形图中不绘制变量的特定条形?下面的示例显示了变量 (aj) 的选择,这些变量具有可能对它们做出贡献的各种因素 (1-5)。注意:“事物”(1-5)对变量(aj)的贡献为零时的间隙。from random import randrange # Make the dataset of data for variables (a-j)columns = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']data = np.array([np.random.randn(5)**2 for i in range(10)])df = pd.DataFrame(data.T, columns=columns)for col in df.columns:      # Set 3 of the 5 'things' to be np.NaN per column    for n in np.arange(3):        idx = randrange(5)         df.loc[list(df.index)[idx], col] = np.NaN    # Normalise the data to 100% of values    df.loc[:,col] = df[col].values / df[col].sum()*100# Setup plotfigsize = matplotlib.figure.figaspect(.33)fig = plt.figure(figsize=figsize)ax = plt.gca()df.T.plot.bar(rot=0, ax=ax)     # Add a legend and showplt.legend(ncol=len(columns))plt.show()
查看完整描述

1 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

正如评论所述,没有内置的功能。您可以探索以下一种方法:


# we will use this to shift the bars

shifted = df.notnull().cumsum()


# the width for each bar

width = 1 / len(df.columns)


fig = plt.figure(figsize=(10,3))

ax = plt.gca()

colors = [f'C{i}' for i in range(df.shape[1])]

for i,idx in enumerate(df.index):

    offsets = shifted.loc[idx]

    values = df.loc[idx]

    ax.bar(np.arange(df.shape[1]) + offsets*width, values, 

           color=colors[i], width=width, label=idx)

    

ax.set_xticks(np.arange(df.shape[1]))

ax.set_xticklabels(df.columns);

ax.legend()

输出:

https://img1.sycdn.imooc.com//65094dac0001bb9005950192.jpg

查看完整回答
反对 回复 2023-09-19
  • 1 回答
  • 0 关注
  • 56 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信