Python plotly_change 标记的颜色

Python plotly_change marker's color

我想自定义标记颜色,因此我制作了 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()

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()