Juan David
Juan David

Reputation: 2797

Put labels in the center of each bar

I've created a bar plot with matplotlib pyplot library, using the following code:

fig = plt.figure(figsize=(15, 15), facecolor='white')
ax_left = fig.add_subplot(221)
ax_left.grid()
ax_left.bar(
            [ix for ix in range(len(resp_tx.keys()))],
            resp_tx.values,
            #align='center',
            tick_label=resp_tx.keys(),
            color='#A6C307',
            edgecolor='white',
        )
        ax_left.tick_params(axis='x', labelsize=10)
        for label in ax_left.get_xticklabels():
            label.set_rotation(45)

Where resp_tx is a pandas Series that looks like this:

APPROVED                           90
ABANDONED_TRANSACTION              38
INTERNAL_PAYMENT_PROVIDER_ERROR    25
CANCELLED_TRANSACTION_MERCHANT     24
ENTITY_DECLINED                     6
CANCELLED_TRANSACTION_PAYER         2
Name: resp_tx, dtype: int64

This is the result but I'm not able to put the labels in the right place. How can I put the tick labels in the center of the bar?

enter image description here

Upvotes: 0

Views: 872

Answers (1)

Juan David
Juan David

Reputation: 2797

I resolved the issue with the following modifications:

 resp_tx = self.tx_per_account[account].resp_tx.value_counts()          
 ax_left = fig.add_subplot(221)                                         
 ax_left.grid()                                                         
 ax_left.bar(                                                           
     [ix for ix in range(len(resp_tx.keys()))],                         
     resp_tx.values,                                                    
     color='#A6C307',                                                   
     edgecolor='white',                                                 
 )                                                                      
 ax_left.set_xticks([ix+0.4 for ix in range(len(resp_tx.keys()))])      
 ax_left.set_xticklabels(resp_tx.keys(), rotation=40, ha='right')       
 ax_left.set_ylim(top=(max(resp_tx.values)+max(resp_tx.values)*0.05))   
 ax_left.set_xlim(left=-0.2)                                            
 #ax_left.spines['top'].set_visible(False)                              
 ax_left.spines['right'].set_visible(False)                             
 #ax_left.spines['bottom'].set_visible(False)                           
 ax_left.spines['left'].set_visible(False)  

enter image description here

Upvotes: 1

Related Questions