Xomuama
Xomuama

Reputation: 153

Changing x ticks labels iteratively

I would like to change the format of my x ticks labels. They are generated thanks to :

range = pd.cut(df['Notional EUR'],
                   bins=[0, 250000, 500000, 1000000, 5000000, 10000000, 50000000, 100000000, 500000000])
range = range.value_counts(sort=False)
range = range.to_frame()
range.columns = ["Effectif"]
chart = sns.barplot(data=range,
                    color = '#F80116',
                    x=range.index.values,
                    y="Effectif")

I would like to format it as follow : (0, 250K] instead of (0, 250000]. I tried several ways such as : xlabels = [f'({l:.2f}, {r:.2f}]'+'K' for l, r in chart.get_xticks()/1000] but without success...

Here is the chart concerned :

enter image description here

Thanks for your help.

Upvotes: 1

Views: 311

Answers (1)

tdy
tdy

Reputation: 41437

If you want all labels to be abbreviated as K (including like 5000K), replace all 000([\]\),]) patterns with K\1:

xticklabels = [re.sub(r'000([\]\),])', r'K\1', label.get_text()) for label in chart.get_xticklabels()]
chart.set_xticklabels(xticklabels)

xticklabels as K

If you want the labels to be abbreviated adaptively (K, M, etc.), you can use something like this human_format() function:

# adapted from https://stackoverflow.com/a/49955617/13138364
def human_format(match):
    num = int(match.group(0))
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num = round(num / 1000.0)
    abbr = ['', 'K', 'M', 'G', 'T', 'P'][magnitude]
    return f'{num:.0f}{abbr}'

xticklabels = [re.sub(r'([0-9]+)', human_format, label.get_text()) for label in chart.get_xticklabels()]
chart.set_xticklabels(xticklabels)

xticklabels abbreviated adaptively

Upvotes: 1

Related Questions