Home > Net >  How to add extra sign to already existing x-ticks label matplotlib?
How to add extra sign to already existing x-ticks label matplotlib?

Time:09-04

Currently, my histogram plot's x-tick labels are [200. 400. 600. 800. 1000. 1200. 1400.]. It represents the rate in dollars. I want to add $ in prefix of these ticks like [$200 $400 $600 $800 $1000 $1200 $1400].

I tried this axs.xaxis.get_majorticklocs() to fetch x-tick labels and axs.xaxis.set_ticks([f"${amount:.0f}" for amount in axs[0, 1].xaxis.get_majorticklocs()]) to set the updated one. I understand that It will throw error as x-tick labels are now string.

Need help! kindly assist how can I do this.

CodePudding user response:

You can use automatic StrMethodFormatter like this:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(100*np.random.rand(20))

# Use automatic StrMethodFormatter
ax.xaxis.set_major_formatter('${x:1.2f}')

plt.show()

enter image description here

CodePudding user response:

You can do it like this:

x = [*range(200,1600,200)]
y = [*range(7)]
fig, ax = plt.subplots()
ax.plot(x,y)
ax.set_xticks(ticks=x, labels=[f"${num}" for num in x])

enter image description here

CodePudding user response:

You might be looking for set_xticklabels, which says:

Set the xaxis' labels with list of string labels.

Here you want to set the ticks to [200. 400. 600. 800. 1000. 1200. 1400.] and the labels to your string values to ensure it is all aligned.

  • Related