numpy 如何去除散点图中奇怪的杂散线[副本]

tpgth1q7  于 2023-03-08  发布在  其他
关注(0)|答案(1)|浏览(436)
    • 此问题在此处已有答案**:

scipy.curve_fit() returns multiple lines(1个答案)
How to avoid zigzag lines in matplotlib pyplot.plot?(1个答案)
7小时前关闭。
我正在处理众所周知的Gapminder数据文件(此处为:https://www.kaggle.com/datasets/tklimonova/gapminder-datacamp-2007?select=gapminder_full.csv

    • df.标题()**:
country     year    population  continent   life_exp         gdp_cap
0   Afghanistan     2007      31889923       Asia     43.828      974.580338
1   Albania         2007       3600523     Europe     76.423     5937.029526
2   Algeria         2007      33333216     Africa     72.301     6223.367465
3   Angola          2007      12420476     Africa     42.731     4797.231267
4   Argentina       2007      40301927   Americas     75.320    12779.379640

我尝试了一个scatter plot,但被出现在图中的许多行弄糊涂了:

plt.style.use('seaborn')

x = np.array(df['gdp_cap'])
y = np.array(df['life_exp'])

plt.scatter(x, y, marker = 'o', alpha = 1)

coeff = np.polyfit(x, y, 2)

plt.plot(x, coeff[0]*(x**2) + coeff[1]*x + coeff[2])

plt.show()

我做错了什么???

juzqafwq

juzqafwq1#

您的第二个绘图会覆盖第一个绘图。请添加另一个plt.show()以防止覆盖:

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

plt.style.use('seaborn')

x = np.array(df['gdp_cap'])
y = np.array(df['life_exp'])

plt.scatter(x, y, marker = 'o', alpha = 1)
plt.show()

coeff = np.polyfit(x, y, 2)
plt.plot(x, coeff[0]*(x**2) + coeff[1]*x + coeff[2])

plt.show()
    • 输出:**

相关问题