2

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?

Grant Zukel
  • 1,153
  • 2
  • 24
  • 48
  • Which line caused the error? You should always post the complete Traceback (formatted as code) – wwii May 22 '18 at 18:23
  • 1
    I doubt you can use strings to fit anything. The page you link to may not be the most reliable source. Better look at respective questions like e.g. [ths one](https://stackoverflow.com/questions/41838037/python-matplotlib-axis-is-blank-for-date-with-trend-line). – ImportanceOfBeingErnest May 22 '18 at 18:52
  • [Curve fitting to a time series ...](https://stackoverflow.com/q/17638137/2823755) – wwii May 22 '18 at 19:01
  • then is there a way to have matplotlib convert epoch times to dates on the labels only so I could use epoch values for the graphing but have it display month values on the x axis? – Grant Zukel May 22 '18 at 19:45

1 Answers1

0

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()
Pinetwig
  • 673
  • 5
  • 13