我正在尝试绘制一组数据,我的 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
有什么想法吗?
最佳答案
当您谈论“仅将纪元时间转换为标签上的日期”时,我认为您的想法是正确的。 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()
关于带有字符串 x 轴标签的 Python matplotlib 趋势线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50474104/