Search code examples
pythoncolorsplotlymarker

Python plotly_change marker's color


I want to customise marker colors and for yhis reason I made SetColor function. But it change only names in legend, but not colors in the visualization. How to fix it?

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

Solution

  • The color parameter in scatter_geo refers to the column of categories, not the colors you want to pick. so you should set the color='bins' and add a new parameter, 'color_discrete_sequence' with the specific colors you want. See below for the code and result:

    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.