亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在散點圖上有多個分類標記

如何在散點圖上有多個分類標記

慕碼人8056858 2023-12-26 16:18:31
我想訓練邏輯回歸模型,然后創建一個以特定方式顯示邊界線的圖。到目前為止我的工作import numpy as npimport matplotlib.pyplot as pltfrom sklearn.linear_model import LogisticRegressionfrom sklearn import datasetsfrom matplotlib.colors import ListedColormapcmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])# import some data to play withiris = datasets.load_iris()X = iris.data[:, :2]  # we only take the first two features.Y = iris.targetlogreg = LogisticRegression(C=1e5)# Create an instance of Logistic Regression Classifier and fit the data.logreg.fit(X, Y)# Plot the decision boundary. For that, we will assign a color to each# point in the mesh [x_min, x_max]x[y_min, y_max].x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5h = .02  # step size in the meshxx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))Z = logreg.predict(np.c_[xx.ravel(), yy.ravel()])# Put the result into a color plotZ = Z.reshape(xx.shape)plt.figure(1, figsize=(4, 3))plt.pcolormesh(xx, yy, Z, cmap=cmap_light)# Plot also the training pointsplt.scatter(X[:, 0], X[:,1], c=Y, marker='x',edgecolors='k', cmap=cmap_bold)plt.xlabel('Sepal length'),plt.ylabel('Sepal width')plt.xlim(xx.min(), xx.max())plt.ylim(yy.min(), yy.max())plt.xticks(())plt.yticks(())plt.show()但是我發現它非常難以閱讀。我想在左上角為每個分類和圖例添加其他標記。就像下圖所示:你知道我該如何改變嗎?我玩過marker ='s', marker='x',但這些改變了散點圖上的所有點,而不是一個特定的分類。
查看完整描述

3 回答

?
烙印99

TA貢獻1829條經驗 獲得超13個贊

由于您正在使用分類值進行繪圖,因此您可以單獨繪制每個類:


# Replace this

# plt.scatter(X[:, 0], X[:,1], c=Y, marker='x',edgecolors='k', cmap=cmap_bold)

# with this


markers = 'sxo'

for m,i in zip(markers,np.unique(Y)):

    mask = Y==i

    plt.scatter(X[mask, 0], X[mask,1], c=cmap_bold.colors[i],

                marker=m,edgecolors='k', label=i)

plt.legend()

輸出:

https://img1.sycdn.imooc.com/658a8d020001b4ec04730353.jpg

查看完整回答
反對 回復 2023-12-26
?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

  • X我發現從&創建數據框Y,然后用 繪制數據點更容易seaborn.scatterplot。

    • seaborn是 matplotlib 的高級 api

    • 如如何從 k-近鄰預測中提取邊界值中所示,數據框列可用于指定要擬合的所有數據以及 x 和 y 的最小值和最大值。

加載并設置數據

import numpy as np

import matplotlib.pyplot as plt? # version 3.3.1

from sklearn.linear_model import LogisticRegression

from sklearn import datasets

from matplotlib.colors import ListedColormap

import seaborn? # versuin 0.11.0

import pandas? # version 1.1.3


cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])

cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])


# seaborn.scatterplot palette parameter takes a list

palette = ['#FF0000', '#00FF00', '#0000FF']


# import some data to play with

iris = datasets.load_iris()

X = iris.data[:, :2]? # we only take the first two features.

Y = iris.target


# add X & Y to dataframe

df = pd.DataFrame(X, columns=iris.feature_names[:2])

df['label'] = Y

# map the number values to the species name and add it to the dataframe

species_map = dict(zip(range(3), iris.target_names))

df['species'] = df.label.map(species_map)


logreg = LogisticRegression(C=1e5)


# Create an instance of Logistic Regression Classifier and fit the data.

logreg.fit(X, Y)


# Plot the decision boundary. For that, we will assign a color to each

# point in the mesh [x_min, x_max]x[y_min, y_max].

x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5

y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5

h = .02? # step size in the mesh

xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

Z = logreg.predict(np.c_[xx.ravel(), yy.ravel()])


# Put the result into a color plot

Z = Z.reshape(xx.shape)

繪制數據圖

plt.figure(1, figsize=(8, 6))


plt.pcolormesh(xx, yy, Z, cmap=cmap_light, shading='auto')

# Plot also the training points


# add data points using seaborn

sns.scatterplot(data=df, x='sepal length (cm)', y='sepal width (cm)', hue='species',

? ? ? ? ? ? ? ? style='species', edgecolor='k', alpha=0.5, palette=palette, s=70)


# change legend location

plt.legend(title='Species', loc=2)


plt.xlim(xx.min(), xx.max())

plt.ylim(yy.min(), yy.max())

# plt.xticks(())

# plt.yticks(())


plt.show()

alpha=0.5與 , 一起使用sns.scatterplot,以顯示 和 的某些值'versicolor'重疊'virginica'。

如果species圖例需要標簽而不是名稱,請更改hue='species'為hue='label'。

https://img1.sycdn.imooc.com/658a8d2c0001c27b09520690.jpg

查看完整回答
反對 回復 2023-12-26
?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

您需要將單個調用更改plt.scatter為每個標記類型的一個調用,因為 matplotlib 不允許像顏色那樣傳遞多個標記類型。


情節代碼變成了類似的東西


# Put the result into a color plot

Z = Z.reshape(xx.shape)


plt.figure(1, figsize=(4, 3))


plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

# Plot also the training points


X0 = X[Y==0]

X1 = X[Y==1]

X2 = X[Y==2]

Y0 = Y[Y==0]

Y1 = Y[Y==1]

Y2 = Y[Y==2]


plt.scatter(X0[:, 0], X0[:,1], marker='s',color="red")

plt.scatter(X1[:, 0], X1[:,1], marker='x',color="blue")

plt.scatter(X2[:, 0], X2[:,1], marker='o',color="green")

plt.xlabel('Sepal length'),

plt.ylabel('Sepal width')


plt.xlim(xx.min(), xx.max())

plt.ylim(yy.min(), yy.max())

plt.xticks(())

plt.yticks(())


plt.show()

您可以在其中單獨設置每個類別的標記類型和顏色。您還可以為標記類型創建一個列表,為顏色創建另一個列表,并使用循環。


查看完整回答
反對 回復 2023-12-26
  • 3 回答
  • 0 關注
  • 210 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號