我试图在plotly中为数据框中的每个类指定颜色,以下是我的代码:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
knn = KNeighborsClassifier(n_neighbors=7)
# fitting the model
knn.fit(X_train, y_train)
# predict the response
pred = knn.predict(X_test)
dfp = pd.DataFrame(X_test)
dfp.columns = ['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm']
dfp["PClass"] = pred
pyo.init_notebook_mode()
data = [go.Scatter(x=dfp['SepalLengthCm'], y=dfp['SepalWidthCm'],
text=dfp['PClass'],
mode='markers',
marker=dict(
color=dfp['PClass']))]
layout = go.Layout(title='Chart', hovermode='closest')
fig = go.Figure(data=data, layout=layout)
pyo.iplot(data)
下面是我的df的样子:
SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm PClass
6.1 2.8 4.7 1.2 Iris-versicolor
5.7 3.8 1.7 0.3 Iris-setosa
7.7 2.6 6.9 2.3 Iris-virginica
所以问题是它没有基于dfp['PClass']
列指定颜色,并且绘图上的每个点都是相同的颜色:黑色。即使在悬停时,每个点都根据其类别正确标记。
知道它为什么不能正常工作吗
在代码示例中,您试图使用
color=dfp['PClass'])
为分类组分配颜色。例如ggplot
和ggplot(mtcars, aes(x=wt, y=mpg, shape=cyl, color=cyl, size=cyl))
应用了这一逻辑,其中cyl
是一个分类变量。您将在页面下方看到一个示例here但对于plotly来说,这是行不通的}中的{}只接受类似于{a2}中带有{}的数值:
color
{为了获得所需的结果,您必须使用多条记录道(如this example)构建绘图:
以下是使用图形对象的示例:
可以使用plotly express执行此操作
相关问题 更多 >
编程相关推荐