CodeMaster
CodeMaster

Reputation: 449

Matplotlib barh yticklabels not displayed correctly

I have the below code implemented to save a barh type plot as a .png file.

    fig, ax = plt.subplots()
    width=0.5
    ind = np.arange(len(df['Count']))  # the x locations for the groups
    ax.barh(ind, df['count'], 0.8, color="blue")
    ax.set_yticks(ind+width/2)
    ax.set_yticklabels(df['UserName'], minor=False,fontsize=6)
    for i, v in enumerate(df['Count']):
        ax.text(v + 4, i + .1, str(v), color='blue')
    plt.xlabel("Count", size=10)
    plt.ylabel("User", size=10)
    plt.title("Distribution", size=12)
    plt.savefig('count.png')  

The code works fine but sometimes the Yticklabels are either not shown or get truncated.

Ex1:

enter image description here

Ex2:

enter image description here

Ex3:

enter image description here

Upvotes: 0

Views: 200

Answers (1)

Oren
Oren

Reputation: 5339

In this line: ax.text(v + 4, i + .1, str(v), color='blue'), you use x,y (position of the text) and add a constant 4, this constant will have different consequences in different plots.

You can try this instead:

ax.text(v + v/4, i + .1, str(v), color='blue')

Now it is related to the value that you are using.

Or you can do:

    v_add = (df['Count'].max())/10
    for i, v in enumerate(df['Count']):
        ax.text(v + v_add, i + .1, str(v), color='blue')

play with these options, change the 4 or the 10 in these examples until you get something reasonable.

Another option is the following (although might not be very accurate)

    fig, ax = plt.subplots()
    width=0.5
    ind = np.arange(len(df['Count']))  # the x locations for the groups
    ax.barh(ind, df['count'], 0.8, color="blue")
    ax.set_yticks(ind+width/2)
    ax.set_yticklabels(df['UserName'], minor=False,fontsize=6)
    max_loc = ax.get_xlim()[1]
    for i, v in enumerate(df['Count']):
        ax.text(max_loc,i + .1 , str(v), color='blue')
    plt.set_xlim(0,max_loc+max_loc/15)
    plt.xlabel("Count", size=10)
    plt.ylabel("User", size=10)
    plt.title("Distribution", size=12)
   

Upvotes: 1

Related Questions