Hi @plotmaster422 ,
I think the idea is making the columns as yaxis label by using transpose
method, so the categories will be set as the index of dataframe.
The number of columns is the number of traces, and every trace can be named as rate (“Bad”,“Good”,…).
import numpy as np
import pandas as pd
import plotly.express as px
colors = ['rgba(38, 24, 74, 0.8)', 'rgba(71, 58, 131, 0.8)',
'rgba(122, 120, 168, 0.8)', 'rgba(164, 163, 204, 0.85)',
'rgba(190, 192, 213, 1)']
data = {'at_home': np.array([8, 1, 7, 4]),
'health': np.array([3, 3, 3, 9]),
'other': np.array([82, 13, 62, 60]),
'services': np.array([41, 14, 30, 26]),
'teacher': np.array([11, 5, 7, 6])}
rates = ["Bad","Neutral","Good","Execllent"]
# create dataframe
df_ori = pd.DataFrame(data)
# get sum over rows
n_samples = df_ori.sum(axis=0)
# calculate the percentage values over rows
df_data = df_ori/n_samples
# transpose data
# so the category will set as y axis labels
# because we will create every trace is by rate
df_data = df_data.T
# adding new columns rates
df_data.columns = rates
# create new column to customize y label
# set y label column as index
df_data['y label'] = ["{} (n={})".format(y.replace("_"," ").title(), val) for y, val in n_samples.to_dict().items()]
df_data = df_data.set_index(['y label'])
# print cleaned data
print(df_data)
# using plotly express make horizontal bar chart
fig = px.bar(df_data,x=df_data.columns, y=df_data.index, color="variable", color_discrete_sequence=colors)
# set barmode to "stack" and
# xaxis format as percent
fig.update_layout(
barmode="stack",
xaxis= dict(
tickformat= '.0%',
title='Percent'
),
yaxis= dict(
title='Category'
),
legend=dict(
title=''
)
)
fig.show()