如果x轴是 pandas 的日期时间索引,如何绘制多色线 [英] How to plot multi-color line if x-axis is date time index of pandas
问题描述
我正在尝试使用pandas系列绘制多色线.我知道matplotlib.collections.LineCollection
将大大提高效率.
但是LineCollection要求线段必须是浮点型的.我想将熊猫的数据时间索引用作x轴.
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?
推荐答案
要生成多色线,您首先需要将日期转换为数字,因为matplotlib在内部仅适用于数字值.
To produce a multi-colored line, you will need to convert the dates to numbers first, as matplotlib internally only works with numeric values.
对于转换,matplotlib提供了matplotlib.dates.date2num
.这了解日期时间对象,因此您首先需要使用series.index.to_pydatetime()
将时间序列转换为日期时间,然后应用date2num
.
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())
然后,您可以照常使用数字点,例如绘制为Polygon或LineCollection [ 1 , 2 ].
You can then work with the numeric points as usual , e.g. plotting as Polygon or LineCollection[1,2].
完整的示例:
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屋!