Position of text automatically changes on graph

2019-08-21 03:47发布

问题:

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.

After 2nd call:

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