带有字符串x轴标签的Python matplotlib趋势线 [英] Python matplotlib trend line with string x axis labels

查看:109
本文介绍了带有字符串x轴标签的Python matplotlib趋势线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制一组数据,这些数据具有y值

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])

我不断得到:

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

有什么想法吗?

推荐答案

当您谈论仅将标签上的时期转换为日期"时,我认为您的想法正确.在这里,您可以看到如何使用Matplotlib的本机date2num将日期时间转换为数字,然后调整图以显示X轴刻度线标记为日期.

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()

这篇关于带有字符串x轴标签的Python matplotlib趋势线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆