python - Plotly-Express:如何在按列名称设置颜色时修复颜色映射

标签 python plotly plotly-express

我正在使用plotlyexpress绘制散点图。标记的颜色由我的数据帧的变量定义,如下例所示。

import pandas as pd
import numpy as np
import plotly.express as px

df = px.data.iris()

fig = px.scatter(df[df.species.isin(['virginica', 'setosa'])], x="sepal_width", y="sepal_length", color="species")
fig.show()

enter image description here

当我添加此变量的另一个实例时,颜色映射会发生变化(首先,“virginica”为红色,然后为绿色​​)。

fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",size='petal_length', hover_data=['petal_width'])
fig.show()

enter image description here

添加变量时如何保持颜色映射?

最佳答案

我找到了解决方案。函数 px.scatter 有一个参数 color_discrete_map ,这正是我所需要的。 color_discrete_map 采用一个字典,其中键是物种的值,值是分配给物种的颜色。

import plotly.express as px    

df = px.data.iris()
color_discrete_map = {'virginica': 'rgb(255,0,0)', 'setosa': 'rgb(0,255,0)', 'versicolor': 'rgb(0,0,255)'}
fig = px.scatter(df[df.species.isin(['virginica', 'setosa'])], x="sepal_width", y="sepal_length", color="species", color_discrete_map=color_discrete_map)
fig.show()

enter image description here

fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", color_discrete_map=color_discrete_map)
fig.show()

enter image description here

关于python - Plotly-Express:如何在按列名称设置颜色时修复颜色映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59713016/

相关文章:

python - 来自 tf.nn.dynamic_rnn 的值错误 : Dimensions must be equal

python - 在数据框中使用分类变量,沿着散点图中的线对线图进行着色

Plotly box p 值显着注释

python - 如何使用 Plotly Express 显示 y 轴上的每个值?

python - Plotly:如何重命名 plotly 表达堆叠条形图的图例元素?

python - 为什么 cx_freeze for Python 3 将一个项目打包成 8000 多个文件,而 cx_freeze for Python 2 将同一个项目打包成 25 个文件?

python - 覆盖 python 日志记录以提高测试效率

python - Cassandra Python 驱动程序 : force using a single node

Python - Dash 从 Excel 文件创建堆积条形图