Pygirl
Pygirl

Reputation: 13349

Adding legend and colour each bar differently

I am trying to plot the distribution of the classes.

import plotly.graph_objects as go
df = pd.read_csv('https://gist.githubusercontent.com/netj/8836201/raw/6f9306ad21398ea43cba4f7d537619d0e07d5ae3/iris.csv')
fig = go.Figure()
fig.add_trace(go.Histogram(histfunc="count",  x=df['variety'], showlegend=True))
fig

This gives me:

enter image description here

I want the legend to be Setosa, Versicolor, Virginica and each bar with different colour.

Using pandas I can do (Although There is problem with legend there):

ax = df['variety'].value_counts().plot(kind="bar")
ax.legend(df.variety.unique())

enter image description here

I want this to be integrated with plotly dash so I am using plotly go. If someone can help me with this issue. It would be a great help to me as I am newbie in plotly.

Upvotes: 2

Views: 577

Answers (1)

jayveesea
jayveesea

Reputation: 3209

One solution is to add each trace individually for all the unique values of variety (or species in my data). When adding each trace use the name argument so that the legend can be populated with the appropriate text. So something like:

import plotly.graph_objects as go
import pandas as pd

df = pd.read_csv('iris.csv')

var = df.species.unique()
fig = go.Figure()
for v in var:
    fig.add_trace(go.Histogram(histfunc="count",  
                               x=df.species[df.species==v], 
                               showlegend=True,
                               name=v
                              )
                 )

fig

enter image description here

Upvotes: 4

Related Questions