I have the following data frame say df =
FunderCode
HCPL1 1% 18% 50% 30% 1%
HCPL2 1% 16% 44% 37% 3%
HCPL3 1% 17% 40% 39% 3%
HCPL4 1% 20% 40% 34% 5%
I wanted to plot it like the following
I could get the following using
Piv_age_per.plot( kind = 'bar', stacked = True , legend = True)
I wanted a diagram with percentage on the bars, if there is inbuilt command to achieve that? g plot I could use the following code to generate
CodePudding user response:
import pandas as pd #1.4.4
import matplotlib.pyplot as plt # 3.5.2
# Python 3.10.6
data = pd.DataFrame(columns=range(5))
data.loc['HCPL1'] = [1, 18, 50, 30, 1]
data.loc['HCPL2'] = [1, 16, 44, 37, 3]
data.loc['HCPL3'] = [1, 17, 40, 39, 3]
data.loc['HCPL4'] = [1, 20, 40, 34, 5]
cumulative = data.cumsum(axis=1)
n_rows, n_cols = data.shape
y_pos = range(n_rows)
height = 0.35
colors = ['blue', 'darkorange', 'gray', 'yellow', 'darkblue']
fig, ax = plt.subplots(figsize=(8, 5))
for i in range(n_cols):
left = cumulative[i]-data[i]
labels = [f'{value:.1f}%' for value in data[i]]
ploted = ax.barh(y_pos, data[i], height,
align='center',
left=left,
zorder=2,
color=colors[i])
ax.bar_label(ploted, label_type='center', fontsize=12, labels=labels)
ax.set_yticks(y_pos, labels=data.index)
ax.invert_yaxis()
ax.tick_params(axis='y', pad=20)
ax.set_xticks(range(0, 101, 10))
ax.grid(axis='x', zorder=0)