0

I would like to annotate my barplot by values in 'region' columns.

    region              year    AveragePrice    Class
162 HartfordSpringfield 2015    1.747788        Most Expensive
215 Houston             2015    1.048077        Less Expensive
108 SanFrancisco        2016    1.881250        Most Expensive
161 Houston             2016    0.991923        Less Expensive
54  SanFrancisco        2017    1.965943        Most Expensive
107 Houston             2017    1.104057        Less Expensive
0   HartfordSpringfield 2018    1.677500        Most Expensive
53  Houston             2018    1.042083        Less Expensive

Here my graphic

Code to create barplot as below:

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(15,7))

ax = sns.barplot(dfx['year'], dfx['AveragePrice'], data = dfx, hue = 'Class', palette = ['lightcoral', 'springgreen'])
plt.xlabel('Year', fontsize = 15)
plt.ylabel('Average Price', fontsize = 15)

Someone can help me ?

1 Answer 1

1

Add the name of a region to the list by the value of a class column from the data frame to make a list for annotations. The list is a multiple list, so it will be flattened. Then, the annotations are set with ax.annotate().

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(15,7))

bplot = sns.barplot(dfx['year'], dfx['AveragePrice'], data = dfx, hue = 'Class', palette = ['lightcoral', 'springgreen'])
plt.xlabel('Year', fontsize = 15)
plt.ylabel('Average Price', fontsize = 15)

txt = []
for c in dfx['Class'].unique():
    tmp = dfx[dfx['Class'] == c]['region']
    txt.append(tmp.tolist())

txt = sum(txt,[])

for t,b in zip(txt, bplot.patches):
    bplot.annotate(t,
                   (b.get_x() + b.get_width() / 2., b.get_height()),
                   ha = 'center', va = 'center',
                   xytext = (0, 9),
                   textcoords = 'offset points')

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.