Python 熊猫在直线上绘制条形图

Python 熊猫在直线上绘制条形图,python,pandas,matplotlib,Python,Pandas,Matplotlib,我想在同一张图上画一条线和一条线。这里是什么有效,什么无效。谁能解释一下原因吗 什么不起作用: 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 = ['

我想在同一张图上画一条线和一条线。这里是什么有效,什么无效。谁能解释一下原因吗

什么不起作用:

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)

但不知何故,当我删除第一个绘图中的
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)

主要问题是
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)
以这种方式处理年份是有意义的,因为不管怎样,您都将年份视为分类数据,并且字母顺序与数字顺序匹配


可能的副本可能也会引起人们的兴趣。我有一种感觉,那就是我只是幸运地让它工作了,这就是为什么我发布了这个问题。解释清楚,解决方案解决了我任务中的几个相关问题。谢谢