How to use plotly.graph_objs
to plot pandas data in a similar way to plotly.express
- specifically to color various data types?
The plotly express functionality to group data types based on a value in a pandas column is really useful. Unfortunately I can't use express in my system (as I need to send the graph object to orca)
I'm able to get the same functionality by specifically mapping Type
to colours (full_plot
in the example below), however I have types A-Z, is there a better way of mapping each possible Type
in the dataframe to a color?
import pandas as pd
import plotly.express as px
import plotly.graph_objs as go
d = {'Scenario': [1, 2, 3, 1, 2,3],
'Type': ["A", "A", "A", "B", "B", "B"],
'VAL_1': [100, 200, 300, 400 , 500, 600],
'VAL_2': [1000, 2000, 3000, 4000, 5000, 6000]}
df = pd.DataFrame(data=d)
def quick_plot(df):
fig = px.bar(df, y='VAL_1', x='Scenario', color="Type", barmode='group')
fig['layout'].update(title = "PX Plot",
width = 600, height = 400,
xaxis = dict(showgrid=False))
fig.show()
def full_plot(df):
colors = {'A': 'blue',
'B': 'red'}
s0=df.query('Type=="A"')
s1=df.query('Type=="B"')
fig = go.Figure()
fig.add_trace(go.Bar(
name='A',
y=s0['VAL_1'],x=s0['Scenario'], marker={'color': colors['A']}))
fig.add_trace(go.Bar(
name='B',
y=s1['VAL_1'],x=s1['Scenario'], marker={'color': colors['B']}))
fig['layout'].update(title = "Full Plot",
width = 600, height = 400)
fig.update_layout(barmode='group')
fig.show()
quick_plot(df)
full_plot(df)
See Question&Answers more detail:
os