Plotting a bar chart, colored by column and with legend displayed

How does one code a bar chart in python so that bars are colored by categories representing thresholds, such as, 'The Good’, ‘The Bad’ and ‘The Ugly’ using the colors 'green, ‘orange’ and ‘red’?

A specific example is the ‘Customizing Individual Bar Colors’ example in the docs - I can’t suss out how to add a legend:

How does one show the legend in this example?

Hi @eddy_oj

The example you’re looking at only creates a single trace and manipulates the color. It sound like you’re wanting to create multiple traces like this example https://plot.ly/python/bubble-charts/#categorical-bubble-charts you could also do this using a for loop https://plot.ly/python/violin/#multiple-traces

For legend styling see https://plot.ly/python/legend/

Hi @bcd

Thank you for helping me. I haven’t had a good opportunity to play around with this until now.

The violin example you linked me to only deals with coloring unique categories that are already on the x-axis - so the coloring adds no value.

My desired solution, which is very common, is to color each bar by a separate column value. e.g.:

data = {'Customer': {13: '6W', 14: '62', 15: '6U', 16: '69', 17: '6T', 18: '68'},
 'FLAG': {13: 'NO FLAG',
  14: 'FLAG',
  15: 'FLAG',
  16: 'FLAG',
  17: 'NO FLAG',
  18: 'FLAG'},
 'Net Amount (Transactional)': {13: 304644580.62070364,
  14: 81045635.64600001,
  15: 10408318.316808157,
  16: 26720780.482699994,
  17: 4913669.359683389,
  18: 10562500.0},
 'color': {13: 'rgb((122, 122, 122)',
  14: 'rgb(255,230,0)',
  15: 'rgb(255,230,0)',
  16: 'rgb(255,230,0)',
  17: 'rgb((122, 122, 122)',
  18: 'rgb(255,230,0)'}}

df = pd.DataFrame(data)

from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)

import plotly.graph_objs as go

data = []
for count, i in enumerate(df['Customer'].unique()):
    trace = {
            "type": 'bar',
            "x": df['Customer'][df['Customer'] == df['Customer'].unique()[count]],
            "y": df['Net Amount (Transactional)'][df['Customer'] == df['Customer'].unique()[count]],
            "marker": {'color': df['color'][df['Customer'] == df['Customer'].unique()[count]],},
            "name": dff.iloc[count]['FLAG'],
            }
        
    data.append(trace)

layout = go.Layout(

     xaxis=dict(type='category'),
                   yaxis=dict(title='Net Amount (Transactional)'))

fig = go.Figure(data=data, layout=layout)

iplot(fig, filename='test', validate=False)

This doesn’t produce a professional plot though as the “FLAG” legend items are duplicated.

Are you able to provide any further guidance on this?