简体   繁体   English

我如何在 Python 中使用 matplotlib plot 一条最佳拟合线?

[英]How can I plot a line of best fit using matplotlib in Python?

I'm trying to plot a line of best fit for this graph.我正在尝试 plot 一条最适合该图的线。 I'm having trouble since x is a categorical variable, and all the solutions I've found don't work if one of them is a categorical variable.我遇到了麻烦,因为 x 是一个分类变量,如果其中一个是分类变量,我发现的所有解决方案都不起作用。

在此处输入图像描述

Here's my code for the plot -这是我的 plot 代码 -

plt.title('Timeline of cases in Maharashtra')

plt.scatter(maharashtra_confirmed['Date'], maharashtra_confirmed['Maharashtra'], label = 'Maharashtra', color = 'orange')
plt.xticks(rotation = 90)
ax = plt.axes()
ax.xaxis.set_major_locator(ticker.MultipleLocator(2))
plt.legend()
plt.show()

For categorical variables, a fit would not make sense from a theoretical view point.对于分类变量,从理论角度来看,拟合是没有意义的。 But what you have here is not per-se categorical data, but (as far as I can guess from your input) just data that can not automatically be interpreted as non-categorical.但是您在这里拥有的不是本身的分类数据,而是(据我从您的输入中猜到的)只是不能自动解释为非分类的数据。

So you have to convert the dates into a more adequate representation.因此,您必须将日期转换为更充分的表示形式。 datetime.datetime.strptime should help you here. datetime.datetime.strptime 应该在这里帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM