Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib plots too many ticks

I have a large code which outputs several images. At times, a plot will look like this (see MWE below):

enter image description here

Notice how the ticks in the x axis are almost overlapping each other, which looks pretty bad.

My question is: why doesn't matplotlib realize this and simply plots fewer ticks (as it usually does without issues)? How can I force matplotlib to draw fewer ticks in a general way (ie: I'm not after a solution that applies only for this particular plot, this is just an example)?


MWE (if the code looks unnecessarily complicated, it's because it's a small portion of a much larger code)

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import random


def scatter_plot(x, y):

    ax = plt.subplot(gs[0:2, 0:2])
    plt.xlim(min(x), 0.00158)
    plt.xlabel('$x$', fontsize=16)
    plt.ylabel('$y$', fontsize=16)
    ax.minorticks_on()

    plt.scatter(x, y)


# Generate random data.
x = [random.random() / 100. for i in xrange(10000)]
y = [random.random() for i in xrange(10000)]
# Define size of output figure.
fig = plt.figure(figsize=(30, 25))  # create the top-level container
gs = gridspec.GridSpec(10, 12)      # create a GridSpec object
# Create plot.
scatter_plot(x, y)
# Save plot to file.
fig.tight_layout()
plt.savefig('out.png', dpi=150)
like image 383
Gabriel Avatar asked Nov 01 '22 08:11

Gabriel


1 Answers

First import numpy as np and then call ax.xaxis.set_ticks(np.arange(xmin, xmax, stepsize)), where xmin is the minimum tick value, xmax is the maximum tick value, and stepsize is the difference between consecutive ticks. It probably makes sense to use stepsize = (xmax - xmin) / tick_count, where tick_count is the number of ticks you want.

like image 144
Noah Halford Avatar answered Nov 15 '22 03:11

Noah Halford