Reputation: 15
I am trying to set specific tick marks on a logarithmic scale:
I found one solution at this link and I will copy and paste the code below:
import matplotlib
from matplotlib import pyplot as plt
fig1, ax1 = plt.subplots()
ax1.plot([10, 100, 1000], [1,2,3])
ax1.set_xscale('log')
ax1.set_xticks([20, 200, 500])
ax1.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
However, the solution converted the tick marks into scalars. I would like to keep the tick marks as scientific notation (i.e., 2x10^1, 2x10^2, 5x10^2)
I found another solution at this link and I will also copy and paste the code below:
import matplotlib
from matplotlib import pyplot as plt
fig1, ax1 = plt.subplots()
ax1.plot([10, 100, 1000], [1,2,3])
ax1.set_xscale('log')
yticks = [2e1, 2e2, 5e2]
ylab=[]
for c,x in enumerate(yticks):
xstr=format(x, '.0e').split('e')
ylab.append(xstr[0]+ ' x $10^{' + xstr[1] +'}$' )
plt.yticks(ticks=yticks,labels=ylab)
However, this solution places a zero digit in front of the exponent, which I also do not want. I want the exponent to not have the zero in the front of it.
Thank you so much!
Upvotes: 0
Views: 204
Reputation: 518
It is a bit rough, but I would do it like this using the math package:
import matplotlib
from matplotlib import pyplot as plt
from math import log10, floor
fig1, ax1 = plt.subplots()
ax1.plot([10, 100, 1000], [1,2,3])
ax1.set_xscale('log')
yticks = [2e1, 2e2, 5e2]
ylab=[]
for c,x in enumerate(yticks):
power = floor(log10(abs(x)))
xstr=format(x, '.0e').split('e')
ylab.append(xstr[0]+ ' x $10^{' + str(power) + '}$' )
plt.yticks(ticks=yticks,labels=ylab)
plt.show()
Output:
Upvotes: 1