我有两个不同的数据框:
df_test1 = pd.DataFrame(
[['<18', 80841], ['18-24', 334725], ['25-44', 698261], ['45-64', 273087], ['65+', 15035]],
columns = ['age_group', 'total_arrests']
)
df_test2 = pd.DataFrame(
[['<18', 33979], ['18-24', 106857], ['25-44', 219324], ['45-64', 80647], ['65+', 4211]],
columns = ['age_group','total_arrests']
)
我使用matplotlib创建了以下图:
fig, ax = plt.subplots()
ax.bar(df_test1.age_group, df_test1.total_arrests, color = 'seagreen')
ax.bar(df_test2.age_group, df_test2.total_arrests, color = 'lightgreen')
ax.set_xlabel('Age Group')
ax.set_ylabel('Number of Arrests')
ax.set_title('Arrests vs. Felony Arrests by Age Group')
plt.xticks(rotation=0)
plt.legend(['All Arressts', 'Felony Arrests'])
ax.yaxis.set_major_formatter(
ticker.FuncFormatter(lambda y,p: format(int(y), ','))
)
for i,j in zip(df_test1.age_group, df_test1.total_arrests):
ax.annotate(format(j, ','), xy=(i,j))
for i,j in zip(df_test2.age_group, df_test2.total_arrests):
ax.annotate(format(j, ','), xy=(i,j))
plt.show()
我期待2个独立的杆,一个用于每个数据帧列,df_test1.total_arrests
并且df_test2.total_arrests
而是我有一个堆积条形图。我怎样才能得到一张条形图彼此相邻的图表,类似于Matplotlib在一个图中绘制多个条形图?在该示例中,我尝试将代码调整为该代码,但无法获取。
只有两个酒吧,这很容易。解决方案是将刻度线的“边缘”上的条对齐,一个条向左对齐,另一条向右对齐。
重复相同的逻辑以正确对齐注释。其中一半左对齐,其他右对齐
fig, ax = plt.subplots()
ax.bar(df_test1.age_group, df_test1.total_arrests, color = 'seagreen', width=0.4, align='edge')
ax.bar(df_test2.age_group, df_test2.total_arrests, color = 'lightgreen', width=-0.4, align='edge')
ax.set_xlabel('Age Group')
ax.set_ylabel('Number of Arrests')
ax.set_title('Arrests vs. Felony Arrests by Age Group')
plt.xticks(rotation=0)
plt.legend(['All Arressts', 'Felony Arrests'])
ax.yaxis.set_major_formatter(
matplotlib.ticker.FuncFormatter(lambda y,p: format(int(y), ','))
)
for i,j in zip(df_test1.age_group, df_test1.total_arrests):
ax.annotate(format(j, ','), xy=(i,j))
for i,j in zip(df_test2.age_group, df_test2.total_arrests):
ax.annotate(format(j, ','), xy=(i,j), ha='right')
plt.show()
如果您的条形超过2条,则情况会更加复杂(请参见上面链接的代码)。使用会更轻松seaborn
,但是您必须对数据框进行一些转换:
df = pd.merge(left=df_test1, right=df_test2, on='age_group')
df.columns=['age_group','all_arrests', 'felonies']
df = df.melt(id_vars=['age_group'], var_name='Type', value_name='Number')
fig, ax = plt.subplots()
sns.barplot(y='Number',x='age_group',hue='Type', data=df, hue_order=['felonies','all_arrests'])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句