简体   繁体   中英

Matplotlib. Can't change the ticks on second y axis

I am drawing a plot with two y-axes, but I can't find a way to modify the ticks on the second y-axis. I get no errors, but the ticks on the right don't change at all.

import matplotlib.pyplot as plt

x = [x for x in range(11)]
y1 = [x for x in range(0, 101, 10)]
y2 = [x for x in range(20, 31, 1)]

fig, ax1 = plt.subplots()
ax2 = plt.twinx()

ax1.plot(x, y1)
ax2.plot(x, y2)

for tick in ax1.yaxis.get_major_ticks():
        tick.label.set_fontsize(30)
        tick.label.set_color('purple')
        
for tick in ax2.yaxis.get_major_ticks():
        tick.label.set_fontsize(30)
        tick.label.set_color('green')
        
plt.show()

I don't know why that doesn't work. If you want to keep your loops (thus preserving the original tick locations), you can access the labels directly:

for label in ax2.yaxis.get_majorticklabels():
    label.set_size(30)
    label.set_color('green')

在此处输入图片说明

If you want to use the matplotlib engine to determine its spacing/location of the ticks based on your new format, you can avoid the loops altogether with:

ax1.tick_params(axis='y', labelcolor='purple', labelsize=30)
ax2.tick_params(axis='y', labelcolor='green', labelsize=30)

在此处输入图片说明

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