熊猫情节条形图在线

Cry*_*tie 2 python matplotlib pandas

我正在尝试在同一个图表上绘制一个条形和一条线.这是有效的,有效的是什么.请问有谁解释原因?

什么不起作用:

df = pd.DataFrame({'year':[2001,2002,2003,2004,2005], 'value':[100,200,300,400,500]})
df['value1']= df['value']*0.4
df['value2'] = df['value']*0.6
fig, ax = plt.subplots(figsize = (15,8))
df.plot(x = ['year'], y = ['value'], kind = 'line', ax = ax)
df.plot(x = ['year'], y= ['value1','value2'], kind = 'bar', ax = ax)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但不知何故,当我x=['year']在第一个图中删除它时它会起作用:

fig, ax = plt.subplots(figsize = (15,8))
df.plot(y = ['value'], kind = 'line', ax = ax)
df.plot(x = ['year'], y= ['value1','value2'], kind = 'bar', ax = ax)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

tmr*_*lvi 5

主要问题是kinds="bar"绘制x轴低端的条形图(因此2001实际上是0),同时kind="line"根据给定的值绘制它.删除x=["year"]刚刚使它根据顺序绘制值(通过运气准确匹配您的数据).

可能有更好的方法,但我知道最快的方法是停止将年份视为一个数字.

df = pd.DataFrame({'year':[2001,2002,2003,2004,2005], 'value':[100,200,300,400,500]})
df['value1']= df['value']*0.4
df['value2'] = df['value']*0.6
df['year'] = df['year'].astype("string") # Let them be strings!
fig, ax = plt.subplots(figsize = (15,8))
df.plot(x = ['year'], y = ['value'], kind = 'line', ax = ax)
df.plot(x = ['year'], y= ['value1','value2'], kind = 'bar', ax = ax)
Run Code Online (Sandbox Code Playgroud)

以这种方式处理年份是有道理的,因为无论如何您将年份视为分类数据,并且字母顺序与数字顺序匹配.

在此输入图像描述