如何在 matplot 上绘制散点趋势线?Python-Pandas

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41635448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:46:22  来源:igfitidea点击:

How can I draw scatter trend line on matplot? Python-Pandas

pandasnumpymatplotlib

提问by zono

I want to draw a scatter trend line on matplot. How can I do that?

我想在 matplot 上绘制散点趋势线。我怎样才能做到这一点?

Python

Python

import pandas as pd
import matplotlib.pyplot as plt
csv = pd.read_csv('/tmp/test.csv')
data = csv[['fee', 'time']]
x = data['fee']
y = data['time']
plt.scatter(x, y)
plt.show()

CSV

CSV

fee,time
100,650
90,700
80,860
70,800
60,1000
50,1200

time is integer value.

时间是整数值。

Scatter chartenter image description here

散点图在此处输入图片说明

回答by zono

I'm sorry I found the answer by myself.

对不起,我自己找到了答案。

How to add trendline in python matplotlib dot (scatter) graphs?

如何在 python matplotlib 点(散点)图中添加趋势线?

Python

Python

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
csv = pd.read_csv('/tmp/test.csv')
data = csv[['fee', 'time']]
x = data['fee']
y = data['time']
plt.scatter(x, y)

z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x,p(x),"r--")

plt.show()

Chart

图表

enter image description here

在此处输入图片说明

回答by Scott Boston

You also can use Seaborn lmplot:

您还可以使用 Seaborn lmplot:

import seaborn as sns

import pandas as pd

from io import StringIO

textfile = StringIO("""fee,time
100,650
90,700
80,860
70,800
60,1000
50,1200""")

df = pd.read_csv(textfile)

_ = sns.lmplot(x='fee', y='time', data=df, ci=None)

Output:

输出:

enter image description here

在此处输入图片说明

回答by Ashot Matevosyan

With text:

有文字:

from sklearn.metrics import r2_score

plt.plot(x,y,"+", ms=10, mec="k")
z = np.polyfit(x, y, 1)
y_hat = np.poly1d(z)(x)

plt.plot(x, y_hat, "r--", lw=1)
text = f"$y={z[0]:0.3f}\;x{z[1]:+0.3f}$\n$R^2 = {r2_score(y,y_hat):0.3f}$"
plt.gca().text(0.05, 0.95, text,transform=plt.gca().transAxes,
     fontsize=14, verticalalignment='top')

enter image description here

在此处输入图片说明