2014-05-05 105 views
10

我想绘制第一栏和第二栏数据为条形图,然后为第三栏数据绘制一条线。将Pandas DataFrame绘制为条形图和线条在同一张图表上

我已经尝试了下面的代码,但是这创建了2个单独的图表,但我希望在一个图表上显示所有图表。

left_2013 = pd.DataFrame({'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'], 
        '2013_val': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 6]}) 

right_2014 = pd.DataFrame({'month': ['jan', 'feb'], '2014_val': [4, 5]}) 

right_2014_target = pd.DataFrame({'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'], 
            '2014_target_val': [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]}) 


df_13_14 = pd.merge(left_2013, right_2014, how='outer') 
df_13_14_target = pd.merge(df_13_14, right_2014_target, how='outer') 
df_13_14_target[['month','2013_val','2014_val','2014_target_val']].head(12) 

plt.figure() 
df_13_14_target[['month','2014_target_val']].plot(x='month',linestyle='-', marker='o') 
df_13_14_target[['month','2013_val','2014_val']].plot(x='month', kind='bar') 

这是我目前得到

kpi dashboard

+1

我设法使用下面的代码得到这个工作 fig,ax = plt.subplots() df_13_14_target [[''''''2014_target_val']]。plot(x ='month',ax = ax,linestyle =' - ',marker ='o',color ='r') df_13_14_target [['''''''2013_val','2014_val']]。plot(x ='month',ax = ax,kind ='bar') 然而,关于如何制作线条重心位于条形的上方 – tfayyaz

回答

19

数据帧绘制方法返回一个matplotlib AxesSubplotAxesSubplots名单。 (参见the docs for plot,或boxplot,例如。)

然后,可以通过同样的轴的下一个绘图法(使用ax=ax)来绘制在相同的轴:

ax = df_13_14_target[['month','2014_target_val']].plot(x='month',linestyle='-', marker='o') 
df_13_14_target[['month','2013_val','2014_val']].plot(x='month', kind='bar', 
    ax=ax) 

import pandas as pd 
import matplotlib.pyplot as plt 

left_2013 = pd.DataFrame(
    {'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 
       'oct', 'nov', 'dec'], 
    '2013_val': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 6]}) 

right_2014 = pd.DataFrame({'month': ['jan', 'feb'], '2014_val': [4, 5]}) 

right_2014_target = pd.DataFrame(
    {'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 
       'oct', 'nov', 'dec'], 
    '2014_target_val': [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]}) 

df_13_14 = pd.merge(left_2013, right_2014, how='outer') 
df_13_14_target = pd.merge(df_13_14, right_2014_target, how='outer') 

ax = df_13_14_target[['month', '2014_target_val']].plot(
    x='month', linestyle='-', marker='o') 
df_13_14_target[['month', '2013_val', '2014_val']].plot(x='month', kind='bar', 
                 ax=ax) 

plt.show() 

enter image description here

+0

感谢您的回答。然而,我有一个很大的问题,就像你有两个酒吧中间的标记对齐。请查看我的图表中的图像,其中标记从左侧开始 - https://www.evernote.com/shard/s175/sh/b412bfc1-2c51-4537-b27a-529052197339/f5082585f691fa91952007fe35898caa/deep/0/Untitled1。 png – tfayyaz

+0

我已经使用pandas v0.13.1添加了用于生成图像的完整代码。 – unutbu

+0

我复制了你的确切代码,我仍然没有得到相同的图像,它仍然全部对齐到左侧。你已经安装了什么版本的matplotlib? – tfayyaz

相关问题