Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

In matplotlib, I am unable to get a grid in the following code (which has a log y axis spanning less than a decade without crossing a power of 10).

from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
x = np.geomspace(0.001,5,101)
y = 10**(-0.2-0.05*(np.log10(x)+0.5)**2)
plt.figure(figsize=[5,5])
ax = plt.gca()
plt.plot(x,y)
plt.xscale('log')
plt.yscale('log')
plt.xlabel('$x$')
plt.ylabel('$y$')
yticks = [0.2,0.3,0.4,0.5,0.6] # should not need to be set!
ax.yaxis.set_major_locator(ticker.FixedLocator(yticks)) # why so complicated?
plt.grid()

unless, I remove

axes.grid : True

from my matplotlibrc. Is there a solution that does not involve editing my matplotlibrc file every time I run into a narrow log axis, nor deleting axes.grid : True in my matplotlibrc file, which would force me include plt.grid in my plots?

My other lines involving grids in my matplotlibrc are

axes.grid.axis       : both    ## which axis the grid should apply to
axes.grid.which      : major   ## gridlines at major, minor or both ticks
grid.linestyle       : dotted  ## was solid
                With axes.grid.which  = 'major' only grid lines are shown for the major ticks. With ax.yaxis.set_major_locator you add major ticks.  With the default settings, the loglocator only has major ticks at the powers of 10, and minor ticks inbetween.  Maybe you want set_major_locator(LogLocator(subs=range(1,10))?
– JohanC
                Dec 5, 2021 at 16:31
                note you can "access" your stylelib with the dictionary matplotlib.rcParams. So you can just say matplotlib.rcParams['axes.grid'] = True in your code and not have to mess with the other file at all
– AJ Biffl
                Dec 5, 2021 at 19:09
                @A J Biffl: your tip is interesting, as one can place matplotlib.rcParams['axes.grid'] = True at the top of the code and not have to type plt.grid() for every plot. A more agreeable solution that I just discovered is to keep axes.grid : True in my matplotlibrc and for this particular code, use plt.grid(True) instead of plt.grid(). But I don't understand why there is this incompatibility between the line in the matplotlibrc and the need to insert True in the plt.grid() line.
– gammarayon
                Dec 5, 2021 at 21:53
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.