我正在使用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()
当我添加此变量的另一个实例时,颜色映射会发生变化(首先,“virginica”为红色,然后为绿色)。
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",size='petal_length', hover_data=['petal_width'])
fig.show()
添加变量时如何保持颜色映射?
最佳答案
我找到了解决方案。函数 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()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", color_discrete_map=color_discrete_map)
fig.show()
关于python - Plotly-Express:如何在按列名称设置颜色时修复颜色映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59713016/