如果 x 轴是 pandas 的日期时间索引,如何绘制多色线 [英] How to plot multi-color line if x-axis is date time index of pandas
问题描述
我正在尝试使用熊猫系列绘制多色线.我知道 matplotlib.collections.LineCollection
会大幅提升效率.但 LineCollection 要求线段必须是浮动的.我想使用熊猫的数据时间索引作为 x 轴.
points = np.array((np.array[df_index.astype('float'), values]).T.reshape(-1,1,2))segment = np.concatenate([points[:-1],points[1:]],axis=1)lc = LineCollection(段)fig = plt.figure()plt.gca().add_collection(lc)plt.show()
但是图片不能让我满意.有什么解决办法吗?
要生成多色线,您需要先将日期转换为数字,因为 matplotlib 在内部仅适用于数字值.
对于转换 matplotlib 提供了 matplotlib.dates.date2num
.这理解日期时间对象,因此您首先需要使用 series.index.to_pydatetime()
将时间序列转换为日期时间,然后应用 date2num
.
s = pd.Series(y, index=dates)inxval = mdates.date2num(s.index.to_pydatetime())
然后您可以像往常一样处理数字点,例如绘制为多边形或 LineCollection[
<小时>由于人们在抽象这个概念时似乎有问题,这里有一段与上面相同的代码,没有使用熊猫和独立的颜色数组:
将 matplotlib.pyplot 导入为 plt导入 matplotlib.dates 作为 mdates将 numpy 导入为 np;np.random.seed(42)从 matplotlib.collections 导入 LineCollection日期 = np.arange("2017-01-01", "2017-06-20", dtype="datetime64[D]" )y = np.cumsum(np.random.normal(size=len(dates)))c = np.cumsum(np.random.normal(size=len(dates)))图, ax = plt.subplots()#先将日期转换为数字inxval = mdates.date2num(dates)点 = np.array([inxval, y]).T.reshape(-1,1,2)segment = np.concatenate([points[:-1],points[1:]],axis=1)lc = LineCollection(segments, cmap="plasma", linewidth=3)# 将颜色设置为日期值lc.set_array(c)ax.add_collection(lc)ax.xaxis_date()ax.autoscale_view()plt.show()
I am trying to plot a multi-color line using pandas series. I know matplotlib.collections.LineCollection
will sharply promote the efficiency.
But LineCollection require line segments must be float. I want to use datatime index of pandas as x-axis.
points = np.array((np.array[df_index.astype('float'), values]).T.reshape(-1,1,2))
segments = np.concatenate([points[:-1],points[1:]], axis=1)
lc = LineCollection(segments)
fig = plt.figure()
plt.gca().add_collection(lc)
plt.show()
But the picture can't make me satisfied. Is there any solution?
To produce a multi-colored line, you will need to convert the dates to numbers first, as matplotlib internally only works with numeric values.
For the conversion matplotlib provides matplotlib.dates.date2num
. This understands datetime objects, so you would first need to convert your time series to datetime using series.index.to_pydatetime()
and then apply date2num
.
s = pd.Series(y, index=dates)
inxval = mdates.date2num(s.index.to_pydatetime())
You can then work with the numeric points as usual , e.g. plotting as Polygon or LineCollection[1,2].
The complete example:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
from matplotlib.collections import LineCollection
dates = pd.date_range("2017-01-01", "2017-06-20", freq="7D" )
y = np.cumsum(np.random.normal(size=len(dates)))
s = pd.Series(y, index=dates)
fig, ax = plt.subplots()
#convert dates to numbers first
inxval = mdates.date2num(s.index.to_pydatetime())
points = np.array([inxval, s.values]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)
lc = LineCollection(segments, cmap="plasma", linewidth=3)
# set color to date values
lc.set_array(inxval)
# note that you could also set the colors according to y values
# lc.set_array(s.values)
# add collection to axes
ax.add_collection(lc)
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_minor_locator(mdates.DayLocator())
monthFmt = mdates.DateFormatter("%b")
ax.xaxis.set_major_formatter(monthFmt)
ax.autoscale_view()
plt.show()
Since people seem to have problems abstacting this concept, here is a the same piece of code as above without the use of pandas and with an independent color array:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np; np.random.seed(42)
from matplotlib.collections import LineCollection
dates = np.arange("2017-01-01", "2017-06-20", dtype="datetime64[D]" )
y = np.cumsum(np.random.normal(size=len(dates)))
c = np.cumsum(np.random.normal(size=len(dates)))
fig, ax = plt.subplots()
#convert dates to numbers first
inxval = mdates.date2num(dates)
points = np.array([inxval, y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)
lc = LineCollection(segments, cmap="plasma", linewidth=3)
# set color to date values
lc.set_array(c)
ax.add_collection(lc)
ax.xaxis_date()
ax.autoscale_view()
plt.show()
这篇关于如果 x 轴是 pandas 的日期时间索引,如何绘制多色线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!