13

Suppose I have a simple plot set up in matplotlib:

fig, ax = plt.subplots(1,1)
p=ax.plot([1,2,3,4,5], [10,9,8,7,6])

How could I add a tick to the x-axis at the value 1.5 with the label "here is 1.5"?

I understand that I could use plt.xticks(), but then I would need to specify all ticks and labels.

1 Answer 1

17

Something like this will work:

import matplotlib.pyplot as plt

x=range(10)
y=range(10)

fig, ax = plt.subplots(1,1)
p=ax.plot(x,y)
ax.set_xticks([1.5])
ax.set_xticklabels(["Here is 1.5"])
fig.show()

enter image description here

If you want to add an additional x-tick:

import matplotlib.pyplot as plt
import numpy as np

x=range(10)
y=range(10)

fig, ax = plt.subplots(1,1)

p=ax.plot(x,y)

xt = ax.get_xticks() 
xt=np.append(xt,1.5)

xtl=xt.tolist()
xtl[-1]="Here is 1.5"
ax.set_xticks(xt)
ax.set_xticklabels(xtl)

fig.show()

enter image description here You can play around with label rotation if you need.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.