熊猫绘制混合线条和线条

时间:2020-06-02 00:42:05

标签: python pandas matplotlib pandas-groupby python-datetime

我有两个groupby运算的结果,第一个m_y_count,采用的是多索引格式(第一列年份和第二列月份):

2007    12    39
2008    1     3
        2     120
2009    6     1000
2010    1     86575
        2     726212
        3     2987954
        4     3598215
        6     160597

而另一个y_count只有几年:

2007    69
2008    3792
2009    5
2010    791

我的问题是:如何在同一图中以不同的(对数)y轴绘制它们,并以m_y_count绘制带条,而y_count绘制带有标记的线?

我的尝试:

ax = y_count.plot(kind="bar", color='blue', log = True)
ax2 = ax.twinx()
m_y_count.plot(kind="bar", color='red', alpha = 0.5, ax = ax2)

这将为两个熊猫系列生成条形图,但是当我尝试在第一行中将其更改为kind="line"时,没有行出现。

关于如何进行的任何提示?谢谢!

1 个答案:

答案 0 :(得分:0)

编辑:

我忘了你想要一个吧。

此外,如果您不想弄乱所有这些datetime的东西,您可以在x轴上将年份绘制为整数(月份为1/12分数)。但是我发现,一旦将所有内容作为时间对象,使用datetime就会非常聪明。


我对直接从pandas绘制内容并不熟悉,但是您可以在matplotlib中轻松地做到这一点。不过,我无法完全复制数据:按照下面的示例,您必须将多索引转换为单个datetimeindex,我认为它是would not be too hard

import datetime as dt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

#making fake data
dates1 = pd.date_range('12-01-2007','06-01-2010',periods=9)
data1 = np.random.randint(0,3598215,9)
df1 = pd.DataFrame(data1,index=dates1,columns=['Values'])
dates2 = pd.date_range('01-01-2006',periods=4,freq='1Y') #i don't get why but this starts at the end of 2006, near 2007
df2 = pd.DataFrame([69,3000,5,791],index=dates2,columns=['Values'])

#plotting
fig, ax = plt.subplots()
ax.bar(df2.index,df2['Values'],width=dt.timedelta(days=200),color='red',label='df2')
ax.set_yscale('log')
ax.set_ylabel('DF2 values',color='red')

ax2 = ax.twinx()
ax2.plot(df1.index,df1['Values'],color='blue',label='df1')
ax2.set_yscale('log',)
ax2.set_ylabel('DF1 values',color='blue')

years = mdates.YearLocator() #locate years for the ticks
ax.xaxis.set_major_locator(years) #format the ticks to just show years
xfmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_formatter(xfmt)

ax.legend(loc=0)
ax2.legend(loc=2)

enter image description here

请您详细说明一下。