Change grid interval and specify tick labels in Matplotlib

Posted on

Question :

Change grid interval and specify tick labels in Matplotlib

I am trying to plot counts in gridded plots, but I am not being able to figure out how I go about it. I want to:

  1. Have dotted grids at an interval of 5

  2. Have major tick labels only every 20

  3. I want the ticks to be outside the plot.

  4. Have “counts” inside those grids

I have checked for potential duplicates such as here and here, but I have not been able to figure it out.

This is my code.

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

for key, value in sorted(data.items()):
    x = value[0][2]
    y = value[0][3]
    count = value[0][4]

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.annotate(count, xy = (x, y), size = 5)
    # Overwrites and I only get the last data point

    # Without this, I get "fail to allocate bitmap" error

plt.suptitle('Number of counts', fontsize = 12)

plt.axis([0, 1000, 0, 1000])
# This gives an interval of 200

majorLocator   = MultipleLocator(20)
majorFormatter = FormatStrFormatter('%d')
minorLocator   = MultipleLocator(5)
# I want minor grid to be 5 and major grid to be 20

filename = 'C:UsersOwlDesktopPlot.png'
plt.savefig(filename, dpi = 150)

This is what I get.

This is what I get.

I also have a problem of overwriting the data points. Could anybody PLEASE help me with this problem?

Asked By: owl


Answer #1:

There are several problems in your code.

First the big ones:

  1. You are creating a new figure and a new axes in every iteration of your loop ?
    put fig = plt.figure and ax = fig.add_subplot(1,1,1) outside of the loop.

  2. Don’t use the Locators. Call the functions ax.set_xticks() and ax.grid() with the correct keywords.

  3. With plt.axes() you are creating a new axes again. Use ax.set_aspect('equal').

The minor things:
You should not mix the MATLAB-like syntax like plt.axis() with the objective syntax.
Use ax.set_xlim(a,b) and ax.set_ylim(a,b)

This should be a working minimal example:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)

ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(minor_ticks, minor=True)

# And a corresponding grid

# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)

Output is this:


Answered By: owl

Answer #2:

A subtle alternative to MaxNoe’s answer where you aren’t explicitly setting the ticks but instead setting the cadence.

import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)

fig, ax = plt.subplots(figsize=(10, 8))

# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)

# Change major ticks to show every 20.

# Change minor ticks to show every 5. (20/4 = 5)

# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')

Matplotlib Custom Grid

Answered By: MaxNoe

Leave a Reply

Your email address will not be published. Required fields are marked *