Hello plotly forum, I have the below code which takes in a dataframe with Funds, Periods (years) and annualized returns. I want to group by Periods and funds and show in a bar chart - I have managed to do so. The only problem is that I want each individual group to be sorted. I canβt seem to find a solution online via chatGPT. Anyone that can help?
import pandas as pd
import plotly.express as px
# Sample data for demonstration purposes
data = {
'Period': ['2021', '2021', '2021', '2022', '2022', '2022', '2023', '2023', '2023'],
'Fund': ['Fund A', 'Fund B', 'Fund C', 'Fund A', 'Fund B', 'Fund C', 'Fund A', 'Fund B', 'Fund C'],
'Annualized Return': [0.10, 0.15, 0.12, 0.08, 0.18, 0.16, 0.07, 0.11, 0.13]
}
graphs = pd.DataFrame(data)
# Sort the data by Period and Annualized Return within each Period
graphs_sorted = graphs.sort_values(by=['Period', 'Annualized Return'], ascending=[True, False])
# Create the bar chart
fig = go.Figure()
# Manually setting colors for each Fund to ensure consistency
color_map = {
'2021': "blue",
'2022': "green",
'2023': "black",
}
colors = [color_map[period] for period in list(graphs["Period"])]
# Add bars with custom colors
for period in graphs["Period"].unique():
temp = graphs.loc[graphs["Period"] == period]
x = [
list(temp["Period"]),
list(temp["Fund"])
]
fig.add_bar(
x=x, # Selecting one value per iteration\
y=temp["Annualized Return"],
marker_color=color_map[period],
)
fig.update_layout(
barmode='group',
plot_bgcolor="white", # Background color
paper_bgcolor="white", # Paper background color
font=dict(family='Arial', size=14, color='black'),
yaxis_tickformat= '.1%',
yaxis=dict(
gridcolor="black", # Y-axis gridline color
zerolinecolor="black",
zerolinewidth=0.5
),
showlegend=False
)
# Show the plot
fig.show()