我从数据集中得到蓝色和最后 30 行红色,使用 python matplotlib 散点图
I get from the dataset blue and the last 30 lines red, with using python matplotlib scatter
如何使用 python matplotlib scatter
编写代码,使我从数据集中获得的 x 值的前 37 行变为蓝色,后 30 行变为红色
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv("bogu.csv",sep = ";")
plt.scatter(df.resim,df.katsayi)
plt.xlabel("resim")
plt.ylabel("katsayi")
#plt.show()
if df.resim[1:37].values:
plt.scatter(x,color="red")
#%% sklearn
from sklearn.linear_model import LinearRegression
linear_reg=LinearRegression()
x = df.iloc[1:,0].values.reshape(-1,1)
y = df.iloc[1:,1].values.reshape(-1,1)
x = x.astype(np.float)
y = y.astype(np.float)
linear_reg.fit(x,y)
#array=np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]).reshape(-1,1) # deneyim
#plt.scatter(x,y)
y_head=linear_reg.predict(x)
plt.plot(x,y_head,color="red",label="linear")
为了复制您的数据集,我创建了一个名为 bogu.csv 的文件,其中 "resim" 列中的数字 x
为 0 到 66,第二列 "katsayi"是 x**2
。
要在 plt.scatter
中着色,您只需将列表传递给 c
关键字即可。使用列表理解迭代 df
的索引,并使颜色 "b"
为蓝色,"r"
为红色。
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("bogu.csv", sep=";")
c = ["b" if x < 37 else "r" for x in df.index]
plt.scatter(df.resim, df.katsayi, c=c)
plt.xlabel("resim")
plt.ylabel("katsayi")
plt.show()
Here is what the final plot produces
希望对您有所帮助!
如何使用 python matplotlib scatter
编写代码,使我从数据集中获得的 x 值的前 37 行变为蓝色,后 30 行变为红色import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv("bogu.csv",sep = ";")
plt.scatter(df.resim,df.katsayi)
plt.xlabel("resim")
plt.ylabel("katsayi")
#plt.show()
if df.resim[1:37].values:
plt.scatter(x,color="red")
#%% sklearn
from sklearn.linear_model import LinearRegression
linear_reg=LinearRegression()
x = df.iloc[1:,0].values.reshape(-1,1)
y = df.iloc[1:,1].values.reshape(-1,1)
x = x.astype(np.float)
y = y.astype(np.float)
linear_reg.fit(x,y)
#array=np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]).reshape(-1,1) # deneyim
#plt.scatter(x,y)
y_head=linear_reg.predict(x)
plt.plot(x,y_head,color="red",label="linear")
为了复制您的数据集,我创建了一个名为 bogu.csv 的文件,其中 "resim" 列中的数字 x
为 0 到 66,第二列 "katsayi"是 x**2
。
要在 plt.scatter
中着色,您只需将列表传递给 c
关键字即可。使用列表理解迭代 df
的索引,并使颜色 "b"
为蓝色,"r"
为红色。
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("bogu.csv", sep=";")
c = ["b" if x < 37 else "r" for x in df.index]
plt.scatter(df.resim, df.katsayi, c=c)
plt.xlabel("resim")
plt.ylabel("katsayi")
plt.show()
Here is what the final plot produces
希望对您有所帮助!