【问题标题】:Plotting lines and bars from pandas dataframe on same graph using matplotlib使用 matplotlib 在同一图表上绘制来自 pandas 数据帧的线条和条形图
【发布时间】:2018-02-15 03:01:12
【问题描述】:

我想将温度数据绘制为一条线,将降雨数据绘制为条形。我可以在Excel 中轻松做到这一点,但我更喜欢花哨的 python 图以更好的方式显示它。

一些示例代码来说明问题:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

dates = pd.date_range('20070101',periods=365)
df = pd.DataFrame(data=np.random.randint(0,50,(365,4)), columns =list('ABCD'))
df['date'] = dates
df = df[['date','A', 'B', 'C', 'D']]
df.set_index(['date'],inplace=True) #set date as the index so it will plot as x axis

这将创建一个包含四列的数据框(假设 A 和 B 是温度,C 和 D 是降雨量)。

我想将降雨量绘制为条形,将温度绘制为一条线,但是当我尝试这样做时:

ax = df.plot(y="A", kind="bar")
df.plot(y="B", kind = "line", ax = ax)

线条绘制但not the bars.

这是我正在尝试做的一个更简单的版本,但我认为它说明了问题。

编辑:

以下代码有效:

fig, ax= plt.subplots()

ax.plot_date(df.index, df.iloc[:,2], '-')

for i in range(3):
    diff = df.index[1]-df.index[0]
    spacing = diff/(1.3*len(df.columns))
    ax.bar(df.index+(-5+i)*spacing, df.iloc[:,i], 
       width=spacing/diff, label=df.columns[i]) 

plt.legend()
plt.gcf().autofmt_xdate()
plt.show() 

非常感谢一个不那么复杂的答案,因为这看起来很冗长,但似乎有效!

【问题讨论】:

  • x 轴不兼容(尝试分别绘制两者)。
  • 我已经编辑了问题以回应您的建议,根据日期创建了一个新的 x 轴,但结果是一样的
  • 因为您的索引是日期时间,所以您确实遇到了同样的问题。您可以将索引转换为字符串表示形式(并且每月仅显示一个刻度标签)。
  • 你读过this question吗?它在多大程度上没有帮助?

标签: python pandas matplotlib


【解决方案1】:

一种简单的方法是使用x_compat 属性:

ax = df.plot(x=index, y="A", x_compat=True)  # plot lines first
df.plot(x=index, y="B", kind="bar", ax=ax)

然后您可以调整滴答频率。

帽子提示:https://stackoverflow.com/a/39907390/5276797

【讨论】:

  • 抱歉 - 但这只会绘制条形图,而不是线形图?
  • 我的错,我贴错了。你仍然需要x=index,请看我的编辑。
  • 嗨 - 很抱歉没有回复你,是的 - 线图和条形图一起绘制!谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-05-06
  • 2014-07-27
  • 2021-02-01
  • 2018-11-26
  • 2019-05-29
  • 2020-02-28
  • 2018-05-27
  • 1970-01-01
相关资源
最近更新 更多