Python plotly_change标记的颜色

问题描述 投票:0回答:1

我想自定义标记颜色,出于这个原因,我进行了SetColor功能。但是它仅更改图例中的名称,而不更改可视化中的颜色。如何解决?

import plotly.express as px
import pandas as pd

rows=[['501-600','15','122.58333','45.36667'],
      ['till 500','4','12.5','27.5'],
      ['more 1001','41','-115.53333','38.08'],
      ]

colmns=['bins','data','longitude','latitude']
df=pd.DataFrame(data=rows, columns=colmns)
df = df.astype({"data": int})

def SetColor(x):
        if(x == '501-600'):
            return "steelblue"
        elif(x == 'till 500'):
            return "mintcream"
        elif(x == 'more 1001'):
            return "palegoldenrod"

fig=px.scatter_geo(df,lon='longitude', lat='latitude',color=list(map(SetColor, df['bins'])),
                      opacity=0.5,size='data',
                      projection="natural earth")

fig.update_traces(marker=dict(symbol='octagon',
                                line=dict(width=0)))

fig.show()
python colors plotly marker
1个回答
0
投票

scatter_geo中的color参数是指类别的列,而不是您要选择的颜色。因此,您应该设置color ='bins'并添加一个新参数'color_discrete_sequence'和所需的特定颜色。参见下面的代码和结果:

import plotly.express as px
import pandas as pd

rows=[['501-600','15','122.58333','45.36667'],
      ['till 500','4','12.5','27.5'],
      ['more 1001','41','-115.53333','38.08'],
      ]

colmns=['bins','data','longitude','latitude']
df=pd.DataFrame(data=rows, columns=colmns)
df = df.astype({"data": int})

# def SetColor(x):
#         if(x == '501-600'):
#             return "steelblue"
#         elif(x == 'till 500'):
#             return "mintcream"
#         elif(x == 'more 1001'):
#             return "palegoldenrod"

fig=px.scatter_geo(df,lon='longitude', lat='latitude',color='bins',
                      opacity=0.5,size='data',
                      projection="natural earth", color_discrete_sequence=['steelblue', 'mintcream', 'palegoldenrod'])

fig.update_traces(marker=dict(symbol='octagon',
                                line=dict(width=0)))

fig.show()

The colors match the bins now.

© www.soinside.com 2019 - 2024. All rights reserved.