问题
I'm trying to graph a set of data I have my y values as
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])
I keep getting:
ufunc 'add' did not contain loop with signature matching type dtype ('S32') ('S32') ('S32')
I have tried using epoch dates as well but that didn’t work. I’m simply trying to plot a trend of prices to dates and extend the trend line past the dates. I know the error has to do with the labels being strings. I’m not sure how to plot the trendline with string labels. The guide I was using has date labels so I’m not sure what I’m doing wrong.
http://widu.tumblr.com/post/43624347354/matplotlib-trendline
Any thoughts?
回答1:
I think you have the right idea when you talk about "converting epoch times to dates on the labels only". Here, you can see how to convert datetimes to numbers using Matplotlib's native date2num and then adjust the plot to display the X-axis tick marks as dates.
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()
来源:https://stackoverflow.com/questions/50474104/python-matplotlib-trend-line-with-string-x-axis-labels