I have a dataframe with following data:
data = {'#': ['2', '3', '7', '9', '10'], 'make': ['Mercedes', 'Mercedes', 'Aston Martin', 'Audi', 'BMW'], 'time': [116.571,117.391, 116.475, 116.593, 116.834]}
df = pd.DataFrame(data)
# sort theoretical lap times ascending
df_sorted = df.sort_values(by='time', ascending=True)
df_sorted = df_sorted.reset_index(deep=True)
What I try to achieve is a bar chart with sorted time values and bar colors given by a dictionary:
colors_make = {
"Audi": "red",
"Aston Martin": "green",
"BMW": "cornflowerblue",
"Accura/Honda": "white",
"Ferrari": "yellow",
"Ford": "blue",
"Lamborghini": "lime",
"McLaren": "magenta",
"Mercedes": "grey",
"Porsche": "darkorange"
}
# create plot
fig_theo = px.bar(df_sorted,
x='#',
y='time',
color='make',
text='theoretical best',
color_discrete_map=colors_make,
hover_data={'#': True},
orientation='v') # Vertical bar chart for better readability
The problem I have is that the sorting is working well but the bar chart is sorted by make and time.
Is there a way to keep the sorting and the colors?
One solution I have found is to set x=df.index - this is curently my best option but I am missing the x-labels.
If I get rid of color=‘make’, then sorting is OK but I am missing the desired bar colors.
Can anyone please help with a solution?
Thank you!