简体   繁体   中英

How to edit matplotlib x-tickmarks to match x-labels

I'm trying to edit the tickmarks and labels on my x-axis to match the data I'm plotting. The two variables (x and bin_river) have a shape of 68 so I want to reduce the number of tickmarks plotted and change the labels for the first and list number in array [x]. Array [x] looks like this

print(x)
[-30 -29 -28 -27 -26 -25 -24 -23 -22 -21 -20 -19 -18 -17 -16 -15 -14 -13 -12 -11 -10  -9  -8  -7  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5 6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23 24  25  26  27  28  29  30  31  32  33  34  35  36  37]

These numbers almost correctly represent the data. In array [x], '-30' actually represents all numbers '<-29' and '37' represents all numbers '>=37'. So I want to want to change the tick labels to represent this. I tried

ax.xaxis.set_major_locator(plt.MaxNLocator(15))
ax.set_xticklabels(['<-29','-25','-20', '-15', '-10', '-5', '0', '5', '10', '15', '20', '25', '30', '35', '>=37'],fontsize=11) 
ax.plot(x,ar_prob, c=cmap(0.6))
ax.set_title('Atmospheric River Landfall Probability',fontsize=16)
plt.grid(True)
ax.set_xlabel('Blocking Index (dam)',fontsize=15)
ax.set_ylabel('AR Landfall Probability',fontsize=15)
ax.set_ylim(0, 100)
plt.show()

在此处输入图片说明

The tickmarks I want are not plotting and the line is misplaced. How do I fit the line to the correct tickmarks and add an irregular tickmark after 35 since the spacing changes?

When setting the xticklabels, it helps to set also explicitely set the xticks. That way they are always aligned, also when zooming.

In the code below, first the tick positions are set as multiples of 5, include the very last position and don't put a tick at 35 as it would be too close.

Then, the string for the labels are formatted, with a special format for the first and the last. A unicode '≥' is used as it is shorter.

from matplotlib import pyplot as plt
import numpy as np

x = list(range(-30, 38))
ar_prob = np.random.uniform(0, 100, len(x))
fig, ax = plt.subplots()
ax.plot(x, ar_prob, c='crimson')
ticks = [i for i in x if i == x[-1] or (i % 5 == 0 and i < x[-1] - 3)]
tick_labels = [f'<{t}' if t == x[0] else f'≥{t}' if t == x[-1] else f'{t}' for t in ticks]
ax.set_xticks(ticks)
ax.set_xticklabels(tick_labels, fontsize=11)
ax.set_title('Atmospheric River Landfall Probability', fontsize=16)
ax.grid(True)
ax.set_xlabel('Blocking Index (dam)', fontsize=15)
ax.set_ylabel('AR Landfall Probability', fontsize=15)
ax.set_ylim(0, 100)
plt.show()

样地

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM