How to ignore a value that exeed from an Axis in Python

Viewed 30

I'm new to python. I'm using python 2.7 and i'm using pandas plot to make a BarChart . here 's my code

my_colors = list(islice(cycle(['#AB82FB','#9A958F','#0131CC', '#EA3C00', '#22DC00','#CCC201','#01BECC','#CC6F01','#8F959A','#02E7D1','#01FF00','#FDF505']), None, len(df)))
df = pd.read_csv(r"/path",sep=';')
data3=df[['DAY_DEPOSE','CHEMIN_REPERTOIRE_SOURCE','TPS_ATTENTE_HOURE']]
tab4=pd.crosstab(index = data3['DAY_DEPOSE'],columns=data3['CHEMIN_REPERTOIRE_SOURCE'],values=data3['TPS_ATTENTE_HOURE'],margins=False,aggfunc='mean')
tab4=tab4[['source_fichier','source_xml']]
fig4=plt.figure()
tab4.plot(kind='bar', color=my_colors,figsize=(20,18))
plt.yticks(np.arange(0, 50, 2))
plt.grid(axis='y')
plt.savefig(r'/path/figure4.png')

and here is my barChart enter image description here

now what i wanna add is : when a value exeed from the maximum value of axis(in our cas '50') , i want it to stop at that value and have a label that indicate its value , for exemple:

enter image description here

Can we do it , would please help me

1 Answers

Consider the following example.

import pandas as pd
import random
import numpy as np

df = pd.DataFrame({'x': [x for x in range(30)],
                   'y': [random.randint(0, 60) for x in range(30)],
                   })

You can recreate a similar plot to the one you have with the following.

plt.figure(figsize=(5,5))
plt.yticks(np.arange(0, 55, 5))
plt.bar(df.x.values, df.y.values)
plt.show()

First Image

You can limit the y-axis, and add labels using something like the following.

plt.figure(figsize=(5,5))
plt.yticks(np.arange(0, 55, 5))
plt.bar(df.x.values, np.where(df.y.values > 50, 50, df.y.values))
plt.ylim(0, 55)

for i in range(len(df.y.values)):
    if df.y.values[i] >= 50:
        plt.annotate(str(df.y.values[i]), xy=(df.x.values[i], np.where(df.y.values > 50, 50, df.y.values)[i]), ha='center', va='bottom')
        
plt.show()

2nd Plot

Related