[Python] Custom tick marks in matplotlib

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 14K views
sk1105
Messages
88
Reaction score
12
I've looked around for this and so far haven't found anything close enough to what I'm after.

In matplotlib, I want to get a specific tick on the x-axis to label a particular value. I know how to use axvline to get a vertical line marking that point, which is good, and I know how to add annotations onto the graph itself, but is there a way of getting an additional tick mark at that particular x value, in addition to the regular marks?

To add some context, I have a graph of the electron-positron annihilation cross-section as a function of collider energy, and I want to mark the mass of the Z boson to point out the resonant behaviour.
 
on Phys.org
The command is set_xticks([x1,x2,x3]). The list can have the ticks wherever you want. Here is some code:

Code:
import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[1,4,9,16,25]

plt.figure()
ax1 = plt.axes()
ax1.plot(x,y)
ax1.set_xticks([0.0,0.37, 1.85, 4.23])
plt.show()
 
Thanks, that does what I want...as well as something I don't want. It completely ruins my subplots. I had 4 plots on a 2x2 grid, and adding that command causes it to show only my fourth subplot, as a full-window figure. I've tried putting the command in a few different places to no avail. Is there a special procedure when using this with subplots?
 
sk1105 said:
Thanks, that does what I want...as well as something I don't want. It completely ruins my subplots. I had 4 plots on a 2x2 grid, and adding that command causes it to show only my fourth subplot, as a full-window figure. I've tried putting the command in a few different places to no avail. Is there a special procedure when using this with subplots?

Sure, you just need to apply the command at the subplot level, like this:
Code:
import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[1,4,9,16,25]

plt.figure()
ax1 = plt.subplot(2,2,1)
ax1.plot(x,y)
ax1.set_xticks([0.0,0.74, 1.85, 4.23])
ax2 = plt.subplot(2,2,2)
ax2.plot(x,y)
ax2.set_xticks([0.0,0.74, 1.85, 4.23])
ax3 = plt.subplot(2,2,3)
ax3.plot(x,y)
ax3.set_xticks([0.0,0.74, 1.85, 4.23])
ax4 = plt.subplot(2,2,4)
ax4.plot(x,y)
ax4.set_xticks([0.0,0.74, 1.85, 4.23])
plt.show()
 
Ah that has solved all my problems. Thanks very much!