【问题标题】:Plot bar graph using matplotlib with different dataframe shape使用具有不同数据框形状的 matplotlib 绘制条形图
【发布时间】:2019-05-24 23:32:21
【问题描述】:

我有三个不同的数据框,如下所示。前两个的形状为 (4,),最后一个的形状为 (2,)。如何转换数据框的形状?

当我尝试在条形图中绘制所有三个时,最后一个 DF 失败并显示“ValueError: shape mismatch: objects cannot be broadcast to a single shape”

如何通过将“空”和“无效”显示为 0 在同一条形图中绘制 DF3。

DF1:

Validity

Empty               2672

InValid              581

Multiple Entries     282

Valid               5526

Name: Lifecycle, dtype: int64

DF2:

Validity

Empty                1920

InValid               471

Multiple Entries     2325

Valid               33446

Name: Lifecycle, dtype: int64

DF3:

Validity

Multiple Entries    10334

Valid               11984

Name: Lifecycle, dtype: int64

下面是我的代码。

glot = sample_lot_number.groupby("Validity")

vlot = sample1_lot_number.groupby("Validity")

dplot = Data_Package_Lot_Number.dplot.groupby("Validity")

ind = np.arange(4)

width = 0.15

ax = plt.subplot()

p1 = ax.bar(ind+width,glot.Lifecycle.count(), width)

p2 = ax.bar(ind,vlot.Lifecycle.count(), width)

p3 = ax.bar(ind-width,dplot.Lifecycle.count(), width)

ax.set_xticks(ind + width / 2)

ax.set_xticklabels(("Empty","InValid","Multiple Entries","Valid"))

【问题讨论】:

  • 使用pandas.DataFrame.reindex 重新索引您的数据框并设置缺失的数据框。它将填充NaN,但如果您愿意,您可以将其更改为0

标签: python pandas numpy matplotlib bar-chart


【解决方案1】:

@busybear 在评论中给出了正确答案。您的代码不可运行。如果我猜一下,你可以试试下面的代码:

glot = sample_lot_number.groupby("Validity")
vlot = sample1_lot_number.groupby("Validity")
dplot = Data_Package_Lot_Number.dplot.groupby("Validity")
df1 = glot.Lifecycle.count()
df2 = vlot.Lifecycle.count().reindex(df1)
df3 = dplot.Lifecycle.count().reindex(df1).fillna(0)

ind = np.arange(4)
width = 0.15
ax = plt.subplot()
p1 = ax.bar(ind+width, df1, width)
p2 = ax.bar(ind, df2, width)
p3 = ax.bar(ind-width, df3, width)
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(("Empty","InValid","Multiple Entries","Valid"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2021-03-11
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    相关资源
    最近更新 更多