【问题标题】:How do you remove spaces between bars in bar charts for where plotted values are zero?您如何删除条形图中的条形之间的空格,以便绘制值为零?
【发布时间】:2021-01-15 08:15:37
【问题描述】:

有时,数据集包含许多变量,其中包含对它们有贡献的其他“事物”的选择。显示这些不同“事物”对变量的贡献(例如百分比)可能很有用。但是,有时并非所有“事物”都对所有变量都有贡献。当绘制为条形图时,当特定变量没有来自“事物”的贡献时,这会导致空格。如果“事物”的贡献为零,有没有办法不为条形图中的变量绘制特定条形?

下面的示例显示了变量 (a-j) 的选择,这些变量具有可能对它们产生影响的各种因素 (1-5)。注意:当“事物”(1-5)对变量(a-j)的贡献为零时的差距。

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 plot
figsize = matplotlib.figure.figaspect(.33)
fig = plt.figure(figsize=figsize)
ax = plt.gca()
df.T.plot.bar(rot=0, ax=ax)     
# Add a legend and show
plt.legend(ncol=len(columns))
plt.show()

【问题讨论】:

  • 可能相关:类似于this comment,不能直接使用pandas,但需要matplotlib 解决方案。

标签: python pandas dataframe matplotlib bar-chart


【解决方案1】:

正如评论的那样,没有内置功能。您可以探索以下方法:

# 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()

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-06
    • 2014-10-30
    • 1970-01-01
    • 2015-08-28
    • 2023-03-12
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多