首页 > 解决方案 > 熊猫情节混合条和线

问题描述

我有两个 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"第一行时,没有出现任何线条。

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

标签: pythonpandasmatplotlibpandas-groupbypython-datetime

解决方案


编辑:

我忘了你想要一个酒吧。

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


我对直接绘制东西不太熟悉pandas,但你可以很容易地在matplotlib. 但是,我无法完全复制您的数据:按照下面的示例,您必须将多索引转换为单个 datetimeindex,我认为这不会太难

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)

在此处输入图像描述

如果您不能将其移植到您的案例中,我可以详细说明。


推荐阅读