Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid overlapping y ticks?

My problem is very simple to explain and maybe the solution too.

I just don’t understand why it is this complicated in matplotlib to build something baisc like I’m trying to do.

I want to make an empty plot with an x from 1 to 12 and and y from 2000 to 2005.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I made the code below but there is two problems :

  • the y ticks are overlapping for some reason
  • there is an extra gap before 1 in the x ticks

enter image description here

I’m using 3.8.2.

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))

plt.xticks(range(1, 13))
plt.yticks(range(2000, 2006))

plt.show()

Can you show me guys how to solve this problem ?

>Solution :

Your issue is that your Y-limits are 0-1 by default, getting extended to 0-2005 after setting your custom axis.

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))

plt.xticks(range(1, 13))
plt.yticks(range(2000, 2005+1))
plt.ylim(2000-0.5, 2005+0.5)  # setting the limits to be 2000-2005 (±0.5)

Output:

Note that this is the same on the X-axis (0-12 instead of 1-12), but less visible. You can perform the same operation on this axis with plt.xlim(1-0.5, 12+0.5).

enter image description here

Generic approach:

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))

Xmin, Xmax = 1, 12
Ymin, Ymax = 2000, 2005
offset = 0.1

plt.xticks(range(Xmin, Xmax+1))
plt.yticks(range(Ymin, Ymax+1))
plt.xlim(Xmin-offset, Xmax+offset)
plt.ylim(Ymin-offset, Ymax+offset)

Output:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading