Python matplotlib trend line with string x axis labels

情到浓时终转凉″ 提交于 2021-02-08 03:01:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!