python - 如何在 matplotlib 和 pandas 中绘制按两列分组的数据框

标签 python pandas matplotlib dataframe bar-chart

我有以下数据框:

                        total_gross_profit
  first_day_week    var 
      Feb-06         1  45293.09
                     2  61949.54
      Feb-13         1  44634.72
                     2  34584.15
      Feb-20         1  43796.89
                     2  37308.57
      Feb-27         1  44136.21
                     2  38237.67
      Jan-16         1  74695.91
                     2  75702.02
      Jan-23         1  86101.05
                     2  69518.39
      Jan-30         1  65913.56
                     2  74823.94
      Mar-06         1  34256.47
                     2  31953.00

first_day_weekvar 列分组我需要制作一个条形图,其中我在 x 轴上有 first_day_week 并且对于 中的每个条目code>first_day_week var 中每个值的两个条形图,颜色不同,类似于(以下条形图的数据完全是假的):

enter image description here

最佳答案

您需要通过 unstack 进行整形然后绘制 DataFrame.plot.bar :

print (df.unstack()['total_gross_profit'])
var                    1         2
first_day_week                    
Feb-06          45293.09  61949.54
Feb-13          44634.72  34584.15
Feb-20          43796.89  37308.57
Feb-27          44136.21  38237.67
Jan-16          74695.91  75702.02
Jan-23          86101.05  69518.39
Jan-30          65913.56  74823.94
Mar-06          34256.47  31953.00


df.unstack()['total_gross_profit'].plot.bar(rot=0)

graph

对于排序索引需要转换为日期时间,排序然后reindex :

df1 = df.unstack()['total_gross_profit']
idx = pd.to_datetime(df1.index, format='%b-%d').sort_values().strftime('%b-%d')
print (idx)
['Jan-16' 'Jan-23' 'Jan-30' 'Feb-06' 'Feb-13' 'Feb-20' 'Feb-27' 'Mar-06']

df1.reindex(idx).plot.bar(rot=90)

graph1

关于python - 如何在 matplotlib 和 pandas 中绘制按两列分组的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42784930/

相关文章:

python - 如何使用 tensorflow 编写摘要日志以对 MNIST 数据进行逻辑回归?

Python - 我的 MySQL 查询中的错误在哪里?

Python matplotlib 图例如何减少帧左边缘和标记之间的距离

python - Matplotlib:将文本与轴刻度对齐

python - 如何安装pybrain

c# - 为什么 JITted Python 实现仍然很慢?

Python Pandas 合并数据框中的同名列

python - Python3.5中列表索引的快捷方式是什么?

python - 使用多索引对数据框进行排序

python - Matplotlib 中的图像处理