我正在尝试绘制一组数据,我将y值设为
y=[129.000, 128.000, 140.000, 150.000]
x=["1/2018", "2/2018", "3/2018", "4/2018"]
# plot the data itself
pylab.plot(x,y,‘o’)
# calc the trendline (it is simply a linear fitting)
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),“r–”)
# the line equation:
print “y=%.6fx+(%.6f)”%(z[0],z[1])
我一直在:
ufunc 'add' did not contain loop with signature matching type dtype ('S32') ('S32') ('S32')
我也尝试过使用纪元日期,但这不起作用。我只是试图将价格趋势绘制成日期,并将趋势线延伸到日期之后。我知道错误与标签是字符串有关。我不确定如何用字符串标签绘制趋势线。我使用的指南有日期标签,所以我不确定我做错了什么。
http://widu.tumblr.com/post/43624347354/matplotlib-trendline
有什么想法吗?
答案 0 :(得分:0)
当你谈到"仅在标签上将纪元时间转换为日期时,我认为你有正确的想法"。 Here,您可以看到如何使用Matplotlib的原生date2num将日期时间转换为数字,然后调整绘图以将X轴刻度标记显示为日期。
from matplotlib import pylab
import numpy
import dateutil
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
y=[129.000, 128.000, 140.000, 150.000]
xStrings=["1/2018", "2/2018", "3/2018", "4/2018"]
# Convert strings to datetime objects,and then to Matplotlib date numbers
dates = [dateutil.parser.parse(x) for x in xStrings]
x = mdates.date2num(dates)
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline (it is simply a linear fitting)
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
polyX = numpy.linspace(x.min(), x.max(), 100)
pylab.plot(polyX,p(polyX),"r")
# the line equation:
print("y=%.6fx+(%.6f)"%(z[0],z[1]))
# Show X-axis major tick marks as dates
loc= mdates.AutoDateLocator()
plt.gca().xaxis.set_major_locator(loc)
plt.gca().xaxis.set_major_formatter(mdates.AutoDateFormatter(loc))
plt.gcf().autofmt_xdate()
pylab.show()