如何减少刻度标签频率而不是刻度总数?

How to decrease the ticks labels frequency but not total number of ticks?

我想每 0.5 个单位显示一次 y 值,但保留现在的刻度频率。我该怎么做?

这是我的代码:

#plotting
ax1.errorbar('Sampling', 'y', data=df3_sub_DP)
ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

ax2.errorbar('Sampling', 'DES', data=df3_sub_DP)
ax2.set(yticklabels=[])
ax2.set(ylabel=None)

# tidy up the figure
ax1.set_ylim((0, 2))
ax2.set_ylim((0, 0.7))

#### some attempts but not working
#ax1.yaxis.set_ticks(np.arange(0, 2, 0.5))
#ax1.yaxis.set_major_locator(plt.MaxNLocator(6))   

plt.show()

谢谢

您可以使用主要和次要刻度:

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

# Some data and the plot
x = np.linspace(0, 2, 20)
y = .5 * x + 1
ax = sns.lineplot(x=x, y=y)


# The labels you want
minor_ticks = np.arange(1, 2.1, .5)  # y values for every .5 units

# The ticks you want
major_ticks = [1.2, 1.7, 1.9] # I've choosen some. You use yours

# Joining things together
g.set_yticks(minor_ticks, minor=True) 
g.set_yticklabels(minor_ticks, minor=True)

g.set_yticks(major_ticks, minor=False)
g.set_yticklabels([], minor=False) # No labels

# And here's the trick:  we set minor ticks length to zero,
# so that only the labels are shown:

ax.tick_params(which="minor", axis="y", length=0)

plt.show()