有時,數(shù)據(jù)集有許多變量,以及一些對它們有貢獻的其他“事物”。顯示這些不同“事物”對變量的貢獻(例如%)可能很有用。然而,有時并非所有“事物”都會對所有變量產(chǎn)生影響。當(dāng)繪制為條形圖時,當(dāng)特定變量沒有“事物”的貢獻時,這會導(dǎo)致出現(xiàn)空格。如果“事物”的貢獻為零,有沒有辦法在條形圖中不繪制變量的特定條形?下面的示例顯示了變量 (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條經(jīng)驗 獲得超10個贊
正如評論所述,沒有內(nèi)置的功能。您可以探索以下一種方法:
# 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()
輸出:
添加回答
舉報
0/150
提交
取消