Reputation: 1521
I have customized the color of data points plotted using plotly. The color of the data points are assigned based on the label associated with it.
However, after setting legend
= True
all three colors(defined in the dictionary) are not displayed in the plot.
I want,
'a': 'rgb(147,112,219)(the actual color in here)',
'b': 'rgb(220,20,60)',
'c': 'rgb(0,128,0)'
to be displayed in the top-right corner of the plot.
import pandas as pd
import plotly as plotly
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
label = ['a', 'b', 'a', 'b', 'c']
label_df = pd.DataFrame({'color': label})
color = {'a': 'rgb(147,112,219)',
'b': 'rgb(220,20,60)',
'c': 'rgb(0,128,0)'
}
cols = label_df['color'].map(color)
data = [
go.Scatter(
x=[1, 2, 3, 4, 5],
y=[1, 2, 3, 4, 5],
mode='markers',
marker=dict(size=10, color=cols)
)
]
layout = go.Layout(
hovermode='y',
showlegend=True,
barmode='stack',
title='plot'
)
fig = go.Figure(data=data, layout=layout)
plot(fig, filename='plot.html')
Any suggestion on how to display the customized legend in the plot?
Here is the figure produced by the code snippet:
Upvotes: 4
Views: 11234
Reputation: 61084
The look and structure of the legend is designed to reflect the content of your figure. What you're aiming to accomplish here is very much possible, but in my opinion best done in a slightly different way. If you'd like all a
labels to have the color 'rgb(147,112,219)'
, and you've got multiple observations of a
, then just construct your figure to show exactly that in order to make the legend make sense. Generally, you'll have one legend element per trace. And you've got one trace. The main difference between your and my approach is that I'm adding one trace per unique label. The code snippet below will give you the following plot which I understand to be your desired result:
Complete code:
import pandas as pd
import plotly.graph_objects as go
df = pd.DataFrame({'label': ['a', 'b', 'a', 'b', 'c'],
'x': [1, 2, 3, 4, 5],
'y': [1, 2, 3, 4, 5]})
color = {'a': 'rgb(147,112,219)',
'b': 'rgb(220,20,60)',
'c': 'rgb(0,128,0)'}
fig = go.Figure()
for lbl in df['label'].unique():
dfp = df[df['label']==lbl]
#print(dfp)
fig.add_traces(go.Scatter(x=dfp['x'], y=dfp['y'], mode='markers',
name=lbl,
marker = dict(color=color[lbl], size = 12)
))
fig.show()
Upvotes: 3