【问题标题】:Matplotliib: Creating multi bar charts for multiple columns from a Pandas dataframeMatplotlib:从 Pandas 数据框中为多列创建多条形图
【发布时间】:2020-05-06 17:47:49
【问题描述】:

我有一个四列的 Pandas 数据框;第一个是中心类型(x 轴),我希望其余列按年份显示为每个中心类型的并排列。我不确定我做错了什么,因为我只获得了 2019 年的值,但我也希望显示 2018 年和 2017 年。

df = c2

colors = ['steelblue','forestgreen','salmon']

ax = df.plot(kind='bar', color=colors, width=0.7, align='center', stacked=False, rot=60, figsize=(12,6), legend=False, zorder=3)


from matplotlib.ticker import FuncFormatter, MaxNLocator
ax.yaxis.set_major_locator(MaxNLocator(integer=True))

plt.grid(zorder=0)
#plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.2))
plt.xlabel("Type of centre")
plt.ylabel("Number")
plt.title("")

ax.spines['bottom'].set_color('gainsboro')
ax.spines['top'].set_color('white') 
ax.spines['right'].set_color('white')
ax.spines['left'].set_color('gainsboro')

ax.yaxis.label.set_color('black')
ax.xaxis.label.set_color('black')

ax.title.set_color('black')

ax.patch.set_facecolor('white')

plt.savefig('images/figure1.png', dpi=300, facecolor=ax.get_facecolor(), transparent=True,  bbox_inches='tight', pad_inches=0.1)
plt.show()
data.shape

【问题讨论】:

  • 如果我像df = pd.DataFrame(np.random.rand(5,3), columns=[2018, 2019, 2020], index=list("ABCDE")) 一样定义df 并运行您的代码,我会得到所需的输出,即this。这意味着您要么没有使用您认为自己使用的数据,要么您使用的是带有错误的特定 pandas 版本。

标签: python pandas matplotlib charts seaborn


【解决方案1】:

您的图片只包含一列的原因是df = c2。 显然 c2 仅包含 DataFrame 中的一列。 删除这条指令。

作为测试,我只执行了:

df.plot.bar(width=0.7, rot=60, figsize=(12,6), legend=False);

得到以下正确的图片,有 5 组条,每组 3 条:

从上面的指令开始,然后决定剩下的 指令应该被实际执行。

在我看来,省略的参数是不需要的,因为它们 传递它们各自的默认值。

还要注意末尾的分号。在 Jupyter Notebook 下工作 只需要渲染图片。 否则(没有终止分号), 打印在图片上。

也许你也应该放弃 legend=False (保持默认 True 值和 打印图例)。 否则不清楚具体的条指的是什么。

【讨论】:

    猜你喜欢
    • 2022-09-30
    • 2019-01-03
    • 1970-01-01
    • 2017-08-31
    • 2021-03-02
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多