1

I have the following dataframe, for which I want to create a plotly scatter chart:

dict1 = {'Name':['Tom', 'nick', 'krish', 'jack','jill'], 
        'Last':[20, 21, 19, 18,15],
         'Change':[-1,-5,1,3,-5],
        'Color':['#30C030', '#9acd32', '#f08080','#FF1E3E','#FF1E3E']}

df = pd.DataFrame(dict1)

I would like the marker color to be the exact color for each item as listed in the 'color' column, however, when I use the following it assigns default colors based on the value in that column, rather than assigning the actual color listed:

fig = px.scatter(df, x = 'Last', y = 'Change', template = 'plotly_dark', 
             text = 'Name', color = 'Color'
            )
fig.update_traces(textposition='bottom center')
fig

Sander van den Oord
  • 10,986
  • 5
  • 51
  • 96
Ben H
  • 145
  • 1
  • 1
  • 4

2 Answers2

2
import pandas as pd
import plotly.express as px

df = pd.DataFrame({'Name': ['tom', 'nick', 'krish', 'jack', 'jill'],
                   'Last': [20, 21, 19, 18, 15],
                   'Change': [-1, -5, 1, 3, -5],
                   'Color': ['#30C030', '#9acd32', '#f08080', '#FF1E3E', '#FF1E3E']})

fig = px.scatter(df, x='Last', y='Change', template='plotly_dark', text='Name')

fig.update_traces(marker=dict(color=df['Color']), textposition='bottom center')

fig.show()
Flavia Giammarino
  • 7,987
  • 11
  • 30
  • 40
  • It would be nice to know why this snippet works, but the one from "Sander van den Oord" does not, when I have CSS colors (ala "#123456") in my "Color" column. The "Sander van den Oord" snippet takes forever for a table of ~80k entries. – Bim Feb 28 '23 at 17:34
0

You can also do this by setting parameter color_discrete_sequence=df['Color'].
You define there the discrete colors to be used:

import pandas as pd
import plotly.express as px

dict1 = {'Name': ['Tom', 'nick', 'krish', 'jack','jill'], 
         'Last': [20, 21, 19, 18,15],
         'Change': [-1,-5,1,3,-5],
         'Color': ['#30C030', '#9acd32', '#f08080','#FF1E3E','#FF1E3E'],}

df = pd.DataFrame(dict1)

fig = px.scatter(
    df, 
    x='Last', y='Change', 
    text='Name', 
    color='Name', 
    color_discrete_sequence=df['Color'],
)

fig.update_traces(textposition='bottom center')

This question + answers contains the same ideas:
Plotly: How to assign specific colors for categories?

There is also a suggestion there to use parameter color_discrete_map where you specifically map names to colors.

Sander van den Oord
  • 10,986
  • 5
  • 51
  • 96