J. *_*eng 5 python matplotlib pandas
我正在尝试使用熊猫系列绘制多色线.我知道matplotlib.collections.LineCollection
会大幅提升效率.但是LineCollection要求线段必须是浮点数.我想使用pandas的数据时间索引作为x轴.
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()
Run Code Online (Sandbox Code Playgroud)
但图片不能让我满意.有什么解决方案吗?
Imp*_*est 10
要生成多色线,您需要先将日期转换为数字,因为matplotlib内部仅适用于数值.
对于matplotlib提供的转换matplotlib.dates.date2num
.这可以理解日期时间对象,因此您首先需要使用series.index.to_pydatetime()
然后应用将时间序列转换为日期时间date2num
.
s = pd.Series(y, index=dates)
inxval = mdates.date2num(s.index.to_pydatetime())
Run Code Online (Sandbox Code Playgroud)
然后,可以用数字点像往常一样,例如如绘制多边形或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()
Run Code Online (Sandbox Code Playgroud)