本文介绍了如何在matplotlib中将条形图和折线图与x轴作为日期时间组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带datetimeIndex的dataFrame和两个带有int值的列.我想在同一张图Col1上绘制条形图,在Col2上绘制线形图.

I have a dataFrame with datetimeIndex and two columns with int values. I would like to plot on the same graph Col1 as a bar plot, and Col2 as a line plot.

重要功能是在放大时也要正确标记x轴为日期时间.我认为使用DateFormatter的解决方案将不起作用,因为我需要动态的xtick标签.

Important feature is to have correctly labeled x-axis as datetime, also when zooming in-out. I think solutions with DateFormatter would not work, since I want a dynamic xtick labeling.

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

startDate = dt.datetime(2018,1,1,0,0)
nrHours = 144
datetimeIndex = [startDate + dt.timedelta(hours=x) for x in  range(0,nrHours)]

dF = pd.DataFrame(index=datetimeIndex)
dF['Col1'] = np.random.randint(1,3,nrHours)
dF['Col2'] = np.random.randint(3,6,nrHours)

axes = dF[['Col1']].plot(kind='bar')
dF[['Col2']].plot(ax=axes)

看似简单的任务却极具挑战性.实际上,在网上进行了广泛搜索之后,我仍然没有找到任何干净的解决方案.

What seemed to be a simple task turns out being very challenging. Actually, after extensive search on the net, I still haven't found any clean solutions.

我尝试同时使用pandas plot和matplotlib.主要问题是由于条形图似乎难以处理日期时间索引(首选整数,在某些情况下,它绘制日期,但采用的是Epoch 1970-1-1样式,它等于0).

I have tried to use both pandas plot and matplotlib.The main issue arises from the bar plot that seems to have difficulties handling datetime index (prefers integers, in some cases it plot dates but in Epoch 1970-1-1 style which is equivalent to 0).

推荐答案

我终于找到了一种使用mdates和date2num的方法.该解决方案不是很干净,但是可以为以下问题提供有效的解决方案:

I finally found a way using mdates and date2num. The solution is not very clean but provides an efficient solution to:

  • 在同一张图中的组合条形图和线形图
  • 在x轴上使用日期时间
  • 正确且动态地显示x-ticks时间标签(以及在放大和缩小时)

工作示例:

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

startDate = dt.datetime(2018,1,1,0,0)
nrHours = 144
datetimeIndex = [startDate + dt.timedelta(hours=x) for x in range(0, nrHours)]

dF = pd.DataFrame(index=datetimeIndex)
dF['Col1'] = np.random.randint(1,3,nrHours)
dF['Col2'] = np.random.randint(3,6,nrHours)

fig,axes = plt.subplots()
axes.xaxis_date()
axes.plot(mdates.date2num(list(dF.index)),dF['Col2'])
axes.bar(mdates.date2num(list(dF.index)),dF['Col1'],align='center',width=0.02)
fig.autofmt_xdate()

样本输出:

这篇关于如何在matplotlib中将条形图和折线图与x轴作为日期时间组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-30 20:52