Reputation: 53
I have some data I want to plot on a log scale, with a specific set of major y-axis ticks
I know I can use something like
plt.scatter(x, y)
ax = plt.gca()
ax.yaxis.set_major_locator(ticker.MultipleLocator(100))
To specify ticks, but I don't know how to pass an instance of matplotlib.ticker.Locator
with arbitrary values e.g. if I want to set the ticks to [2,4,100] instead of fixed increments. How do I turn an array of tick values to an object that set_major_locator
will accept?
Upvotes: 0
Views: 2475
Reputation: 3128
Any reason you don't want to just use the call to yticks
?
x = [1,2,3,4,5]
y = [2,10,40,50,100]
tick_array = [2, 4, 100] # an array of tick values
plt.scatter(x, y, s=150)
plt.yticks(ticks=tick_array)
plt.show()
Forcing the labels to be what you want by setting the labels of your yticks manually.
# Superscript 0-9
print('\u2070', '\u00b9', '\u00b2', '\u00b3', '\u2074',
'\u2075', '\u2076', '\u2077', '\u2078', '\u2079')
x = [1,2,3,4,5,6]
y = [2,10,40,1020,50,100]
plt.yscale("log")
tick_array = [2, 4, 100,1000]
labels = [f'{int(x/100)}\u00b3' if x > 999 else # if x is >= 1000 set superscript 3
f'{int(x/10)}\u00b2' if x > 99 else # if x is >= 100 set superscript2
x for x in tick_array]
plt.scatter(x, y, s=150)
plt.yticks(ticks=tick_array, labels=labels)
plt.show()
⁰ ¹ ² ³ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ # Output of the print statement
Upvotes: 1