可视化同一数据集中的两列

时间:2019-04-22 14:25:35

标签: python matplotlib bar-chart plotly data-visualization

enter image description here

我正在尝试对四列进行分组和排序,对值进行计数并将其绘制在同一条形图中,以查看计数如何变化的趋势。

Image

Year  Month  Bl_year  Month
2018  Jan     2019     Jan 
2018  Feb     2018     Mar
2018  Dec     2020     Dec 
2019  Apr     2019     Sep  
2020  Nov     2020     Dec 
2019  Sep     2018     Jan

我尝试首先进行分组和排序,然后按年份先计算值,然后再按月进行计数。

df_Activity_count = df.sort_values(['year','month'],ascending = True).groupby('month')
df_Activity_count_BL = df.sort_values(['BL year','BL month'],ascending = True).groupby('BL month')

现在,我试图在同一栏中比较这两个。有人可以帮忙吗。

2 个答案:

答案 0 :(得分:1)

尝试将ax传递给绘图命令:

df_Activity_count = df.sort_values(['year','month'],ascending = True).groupby('month')
df_Activity_count_BL = df.sort_values(['BL year','BL month'],ascending = True).groupby('BL month')

ax = df_Activity_count.years.value_counts().unstack(0).plot.bar()
df_Activity_count_BL['BL year'].value_counts().unstack(0).plot.bar(ax=ax)

答案 1 :(得分:0)

自从您标记了matplotlib之后,我将使用pyplot

解决方案
import matplotlib.pyplot as plt

# Create an axis object
fig, ax = plt.subplots()

# Define dataframes
df_Activity_count = df.sort_values(['year','month'],ascending = True).groupby('month')
df_Activity_count_BL = df.sort_values(['BL year','BL month'],ascending = True).groupby('BL month')

# Plot using the axis object ax defined above
df_Activity_count['year'].value_counts().unstack(0).plot.bar(ax=ax)
df_Activity_count_BL['BL year'].value_counts().unstack(0).plot.bar(ax=ax)