如何在matplot上绘制散点趋势线? Python的熊猫

时间:2017-01-13 13:12:23

标签: pandas numpy matplotlib

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

的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

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

时间是整数值。

散点图enter image description here

3 个答案:

答案 0 :(得分:16)

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

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

的Python

@FunctionalInterface
interface Callback {
    void callback(EntityManager e);

图表

enter image description here

答案 1 :(得分:0)

带有文字:

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

答案 2 :(得分:0)

您还可以使用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)

输出:

enter image description here