2

I have a scatter plot created in matplotlib in python where the x-axis is the date and the y-axis is the time. I would like to add some padding to my y-axis so the points aren't cut off at the top and bottom. I've heard of setting ax.ylim([x,y]) to be a little bit smaller than the smallest value and a little bit larger than the largest value but this is impossible with time as there is no such thing as negative time or 25:00.

This is what the image looks like now: enter image description here

As you can see the points at the top and bottom are cut off.

Any help would be greatly appreciated!

Conner Leverett
  • 573
  • 2
  • 7
  • 21
  • Does this work http://stackoverflow.com/questions/2969867/how-do-i-add-space-between-the-ticklabels-and-the-axes-in-matplotlib – Ben Apr 14 '16 at 19:18
  • Or http://stackoverflow.com/questions/6406368/matplotlib-move-x-axis-label-downwards-but-not-x-axis-ticks – Ben Apr 14 '16 at 19:19
  • It's possible for you to write the labels yourself and that would do what you are requesting but that wouldn't leave your plot less crowded, much the opposite (if you give a pad than there will be less space for the plot). Do you want the solution for this anyway? – armatita Apr 14 '16 at 19:23
  • @armatita Sorry, I phrased that incorrectly, I'm not worried about the visualization being crowded, I just don't want the points to be cut off at the top and bottom of the image. – Conner Leverett Apr 14 '16 at 19:31
  • Have you tried left-pad? j/k – drum Apr 14 '16 at 19:34

1 Answers1

3

Here is how you can write your how labels without (and adding limits to data) risking having stupid values there:

import matplotlib.pyplot as plt
import numpy as np

x = np.random.randint(2004,2017,500)
y =np.clip(np.random.normal(13,7,500),0,24)

plt.scatter(x,y)
plt.xticks(range(2004,2017,3),[str(i) for i in range(2004,2017,3)],rotation=45)
plt.yticks(range(0,24,3),[str(i)+':00' for i in range(0,24,3)])

plt.xlim(2002,2019)
plt.ylim(-3,28)
plt.show()

, the result is:

Controlling the labels to have a pad effect

armatita
  • 12,825
  • 8
  • 48
  • 49
  • Thanks for the response! Using your method the spacing works but then my values disappear. Could it be because I'm using datetime.datetime classes for my values? `date = datetime.datetime(int(date[0:4]), int(date[5:7]), int(date[8:10])) dateList.append(date) timeThing = datetime.datetime(2016,1,1,hour,minute) timeList.append(timeThing) plt.scatter(dateList, timeList, c='r' ) plt.yticks(range(0,24,3),[str(i)+':00' for i in range(0,24,3)]) plt.ylim(-3,28)` – Conner Leverett Apr 14 '16 at 20:43
  • @ConnerLeverett Possibly. In the line where you define the `yticks` with the `range(0,24,3)` try putting the dates iterable instead of range. Also put your code (imports included) in the question. It's difficult to read it in a comment. – armatita Apr 14 '16 at 20:55