I'm trying to annotate a simple bar chart that I coded in seaborn. The problem is that the index value is being unable to get converted to an axis unit. I'm not sure why this is happening because I have annotated a previous chart in matplotlib. Here's a sample data frame:
# Note Q5 is the index
print(df)
Q5 Man Woman
A 50 55
B 10 11
C 20 30
The code is just plain simple. Based on Q5 as index, I've plotted values for men and women in two separate subplots. Now the annotating part. I'm simplifying the reproduced code here and also skipping the for loop, but say I use the first value for "A" for Man
for annotation.
fig, ax = plt.subplots(2,1, figsize=(6, 8))
sb.barplot(x=df.Man, y=df.index, data=df, color='lightblue', ax=ax[0])
ax[0].annotate(format(df.Man["A"], xy=(age_occu.Man["A"], "A"))
# And I get this error
matplotlib.units.ConversionError: Failed to convert value(s) to axis units: 'A'
As usual I've tried several other ways, like instead of mentioning "A" as the y parameter, I specify 0 for the top most y entry. But I'm not getting past this error.
Note: Also saving the plot is returning the same error.
This is because the annotate() does not recognize 'A' as the coordinate. You need to retrieve the actual location of the data in plot:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
# Note Q5 is the index
df = pd.DataFrame({'Man':[50, 10, 20], 'Woman':[55,11,30]}, index = pd.Index(['A','B','C'], name='Q5'))
fig, ax = plt.subplots(2,1, figsize=(6, 8))
s = sb.barplot(x=df.Man, y=df.index, data=df, color='lightblue', ax=ax[0])
for i in range(len(df)):
ax[0].annotate(s.patches[i].get_width(),
xy=(s.patches[i].get_width(),
s.patches[i].get_y() + s.patches[i].get_height()/2))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.