python - 在 Plotly 散点图中按颜色添加图例

标签 python plotly

trace = go.Scatter(
x=x_pca_df['Principle'],
y=x_pca_df['Second'],
mode='markers',
marker=dict(color=home_data['PriceLevel'], size=4, showscale=False))

data = [trace]

layout = dict(
title='PCA Analysis',
xaxis=dict(title='First Principle Component'),
yaxis=dict(title='Second Principle Component'))
fig = dict(data=data, layout=layout)
iplot(fig)

我想在这个 plotly 图的侧面显示图例。因此,人们可以理解点的颜色代表什么。我在任何地方都找不到合适的解决方案。
enter image description here

enter image description here

最佳答案

我认为这里的问题有两个方面,首先你的 PriceLevel 是一个整数,所以 plotly 使用它作为一个尺度,这就是你指定 showscale=False 的原因。 .如果您将其更改为 showscale=True你会得到各种各样的图例,但它是一个比例尺,你需要积分。

这是第二部分;如果要将它们显示为单独的刻度,则必须将它们设置为单独的迹线。

例如

# Set up a trace for each level of PriceLevel
trace1 = go.Scatter(
x=x_pca_df.query(" PriceLevel==1")['Principle'],
y=x_pca_df.query(" PriceLevel==1")['Second'],
# Add a name for each trace to appear in the legend
name = 'PriceLevel 1', 
mode='markers',
marker=dict(color='rgba(152, 0, 0, .8)', size=4, showscale=False))

trace2 = go.Scatter(
x=x_pca_df.query(" PriceLevel==2")['Principle'],
y=x_pca_df.query(" PriceLevel==2")['Second'],
name = 'PriceLevel 2', 
mode='markers',
marker=dict(color='rgba(255, 182, 193, .9)', size=4, showscale=False))

# Join them all together 
data = [trace1, trace2]

layout = dict(
title='PCA Analysis',
xaxis=dict(title='First Principle Component'),
yaxis=dict(title='Second Principle Component'))
fig = dict(data=data, layout=layout)
iplot(fig)

希望这会奏效。

关于python - 在 Plotly 散点图中按颜色添加图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52020122/

相关文章:

python - django.core.exceptions.ImproperlyConfigured : Error loading MySQLdb module:

Python - Django 2.2 中的多用户类型实现

python - 决策树只预测一类

python - 如何将非 ascii 字符打印为\uXXXX 文字

Python plotly : Slider not Refreshing Scatter Plot

python - 如何为单个 URL 参数传递多个值?

python - 使用 "plotnine"库绘制表面 3D 图

python - 如何创建一个下拉菜单来更改用于为分区统计图着色的列? ( plotly 快报)

python - Plotly:如何创建奇数个子图?

python - Plotly:如何在直方图中同时显示正态分布和核密度估计?