Python 两个数据帧在多个子包中一起广播
我想绘制5个不同的子图,一个用于每年的数据。每年,我都要展示每个县的DEM和代表。到目前为止,我已经编写了以下代码:Python 两个数据帧在多个子包中一起广播,python,pandas,matplotlib,plot,Python,Pandas,Matplotlib,Plot,我想绘制5个不同的子图,一个用于每年的数据。每年,我都要展示每个县的DEM和代表。到目前为止,我已经编写了以下代码: fig = plt.figure(figsize=(13,10)) plt.subplot(3, 2, 1) plt.bar(data=districts_2018[['DEM', 'REP']], x=districts_2018.index, height=(districts_2018[['DEM', 'REP']])) plt.su
fig = plt.figure(figsize=(13,10))
plt.subplot(3, 2, 1)
plt.bar(data=districts_2018[['DEM', 'REP']],
x=districts_2018.index,
height=(districts_2018[['DEM', 'REP']]))
plt.subplot(3, 2, 2)
plt.bar(data=districts_2017[['DEM', 'REP']],
x=districts_2017.index,
height=districts_2017['DEM'])
plt.subplot(3, 2, 3)
plt.bar(data=districts_2016[['DEM', 'REP']],
x=districts_2016.index,
height=districts_2016['DEM'])
plt.subplot(3, 2, 4)
plt.bar(data=districts_2015[['DEM', 'REP']],
x=districts_2015.index,
height=districts_2015['DEM'])
plt.subplot(3, 2, 5)
plt.bar(data=districts_2014[['DEM', 'REP']],
x=districts_2014.index,
height=districts_2014['DEM'])
plt.tight_layout();
但是,与第一个子批次3,2,1的情况一样,我得到了错误:
ValueError:形状不匹配:无法将对象广播到单个形状。如果我只将高度设置为districts_2018['DEM'],则此代码有效,但仅显示DEM,而不显示代表。您可以直接使用pandas包装器绘制分组条形图。将ax设置为要在其中显示绘图的相应子绘图
fig, axes = plt.subplots(3,2,figsize=(13,10))
for ax, df in zip(axes.flat, [districts_2018, districts_2017, ....])
df[['DEM', 'REP']].plot.bar(ax=ax)
plt.bar中的参数顺序似乎是错误的。一个per,第一个参数是x,然后是高度,然后是宽度。尝试打印districts_2016['DEM']`看看它与districts_2018['DEM',REP']]有什么不同好吧,我拿出数据,现在只有:plt.subplot 3,2,1 plt.barx=districts_2018.index,height=districts_2018['DEM',REP']]但仍然存在错误:形状不匹配:无法将对象广播到单个Shaperay打印不同高度以检查shapebar只能打印单个数据序列,这就是为什么height=districts_2018['DEM']按预期工作的原因。如果要绘制两个序列,需要调用两次bar。好的,我这样调用了两次bar:plt.subplot 3,2,1 plt.bardata=districts\u 2018['DEM'],x=districts\u 2018.index,height=districts\u 2018['DEM']plt.bardata=districts\u 2018['REP'],x=districts\u 2018.index,height=districts\u 2018['REP']但现在它绘制的图中,两条横杆相互重叠——我希望它们并排显示高度上的差异