0

I have a function that generates graph based on values in a dataframe. The code looks like:

def generate_graph(data, title):

    df1 = data['User'].value_counts(sort=False).to_frame()
    plt.figure(figsize=(24, 12))

    graph = sns.barplot(x=df1.index,y=df1.User)
    graph.set_ylabel('ABC ',fontsize=25)
   
    i = 0 
    for p in graph.patches:
        height = p.get_height()
       
        graph.text(p.get_x()+p.get_width()/2., height - 0.1, df1['User'][i], ha="center", fontsize=15)
    

Now, I call this function for multiple dataframes:

generate_graph(dataframe1, 'dataframe1')
generate_graph(dataframe2, 'dataframe2')

When I call the function twice, the position of text on graph varies everytime. Please see the images.

enter image description here

After 2nd call:

enter image description here

Can anyone suggest me a way to avoid this change in the position of the text.

Community
  • 1
  • 1
Tjs01
  • 457
  • 2
  • 8
  • 14
  • There are unfortunately some hundreds of answers on how to annotate bar plots. Only some 2% of them show the most useful solution, which is to use `annotate` and its `textcoords="offset points"` argument to make the annotation position independed of the axis scale. – ImportanceOfBeingErnest Mar 13 '19 at 14:20
  • 1
    Yeah, I had tried many solutions from those, this one did work though. However, can you suggest me a solution with textcoords – Tjs01 Mar 13 '19 at 14:33
  • While I was searching for it, yet another not so great solution appeared. [Here](https://stackoverflow.com/questions/25447700/annotate-bars-with-values-on-pandas-bar-plots#comment39708520_25449186) is a comment that nails it, though there should be real answers as well... somewhere... in between all the rest... – ImportanceOfBeingErnest Mar 13 '19 at 14:37
  • 1
    [This question](https://stackoverflow.com/questions/42697701/optimization-of-bar-plots-in-matplotlib-pandas) and [this question](https://stackoverflow.com/questions/40783669/stacked-bar-plot-by-group-count-on-pandas-python) has it correct. – ImportanceOfBeingErnest Mar 13 '19 at 14:50
  • The general solution is also shown in the matplotlib docs [here](https://matplotlib.org/devdocs/gallery/lines_bars_and_markers/barchart.html). This is a link to the not yet published version because I updated it only recently. – ImportanceOfBeingErnest Mar 13 '19 at 14:58
  • @ImportanceOfBeingErnest I'm happy you've added this to the docs. I'd been searching for the ```annotate``` and ```textcoords="offset points"``` solution, but instead kept finding ```ax.text``` solutions (which I know is inferior, but I'd stuck with because I didn't really understand the ```annotate``` solution until now). – jwalton Mar 13 '19 at 15:21

0 Answers0