问题
Hi I am currently plotting stacked horizontal bar chart using dataframe. The code is as below
new_data.plot.barh(stacked = True)
I get a chart like below.
Ideally I would want to have the data values displayed inside it, like below.
How do I accomplish this? Any help is appreciated. Thanks
回答1:
there's a similar question here, just use ax.text
and adjust the x and y positioning according to your bar value and bar enumeration, for example:
import pandas as pd
df = pd.DataFrame({'value1':[10, 30, 20],'value2':[20,50,10]})
ax = df.plot.barh(stacked = True);
print(df)
for rowNum,row in df.iterrows():
xpos = 0
for val in row:
xpos += val
ax.text(xpos + 1, rowNum-0.05, str(val), color='black')
xpos = 0
display(ax)
来源:https://stackoverflow.com/questions/54162981/how-to-display-data-values-in-stacked-horizontal-bar-chart-in-matplotlib