Home > OS >  Showing the starting value on log scale other than the power of 10 using matplotlib
Showing the starting value on log scale other than the power of 10 using matplotlib

Time:01-29

I have been facing the challenge of showing the starting value on the x-axis with a logarithmic scale. which is other than the power of 10. Unfortunately, I cannot find a way to show this starting value on x-axis. I am using matplotlib and the major constraint is that I have to keep the formatting of the graph as it is therefore please suggest a way that solves the issue without changing the existing formatting.

Code:

   plt.plot(xdata,ydata)
   plt.xscale("log")
   plt.xlim([0.15, 30])
   plt.ylim([-10, 80])
   plt.minorticks_on()
   plt.grid(which = 'minor', linestyle=':', linewidth = '0.5', color = 'black')
   plt.grid(b = True, which = 'major', linestyle='-', linewidth = '1', color = '#666666')
   plt.show()

Current output

Desired output

CodePudding user response:

If you don't mind having the intermediate tick labels in regular format (not engineering format), this could work:

import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter
import numpy as np


xdata = np.logspace(np.log10(0.15), np.log10(30))
ydata = np.random.random(len(xdata))

fig, ax = plt.subplots()
ax.plot(xdata, ydata, '-s')
ax.set_xscale("log")

Once you have the plot, you can manually set the ticks with:

ax.set_xticks([0.15, 1, 10, 30])
ax.get_xaxis().set_major_formatter(ScalarFormatter())

to get: enter image description here

  •  Tags:  
  • Related