Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

python - Errors plotting a trendline using matplotlib and numpy

Edited to include full code and after attempting one solution:

I'm getting an error: UFuncTypeError: ufunc 'add' cannot use operands with types dtype('<M8[ns]') and dtype('float64') when following a tutorial to try and plot a trendline on a scatterplot I created, here's the code:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_csv('dataSet.csv')

date = df['Date'].astype('datetime64')
actual = df['Actual'].astype('float64')

plt.figure(figsize=(20,10))
plt.scatter(date, actual, color='orange')

z = np.polyfit(date, actual, 1)
p = np.poly1d(z)

plt.plot(date, p(date), "r--")

plt.show()

if I replace the formula for z with:

z = np.polyfit(list(date), actual, 1)

it's a slightly different error, but still an error: TypeError: unsupported operand type(s) for +: 'Timestamp' and 'float'

question from:https://stackoverflow.com/questions/65913718/errors-plotting-a-trendline-using-matplotlib-and-numpy

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I just tried this method with your dataset, and it worked:

df["Date"] = pd.to_datetime(df["Date"])
plt.scatter(df["Date"]), df["Actual"])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...