Saad
Saad

Reputation: 1360

Matplotlib: last y tick label not visible with 0 margins

I am drawing a cdf, where I want the y tick labels to be 0, .2, .4, .6, .8, 1. Here's how I'm achieving it.

import matplotlib.pyplot as plt
import numpy as np

# some code

fig, ax = plt.subplots(figsize=(14, 5))
ax.set_yticklabels(np.around(np.arange(0, 1.1, step=0.2),1))
plt.margins(0)
...
plt.show()

This gives the following output:

enter image description here

When I comment out plt.margins(0), I get the following figure:

enter image description here

Why am I not able to see the top most y tick label (1.0) in the first figure? How can I achieve it with 0 margins?

Upvotes: 1

Views: 4854

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339440

If your data ranges from 0 to 1. It will plot 1 in the top left corner.

import matplotlib.pyplot as plt
import numpy as np

data = np.linspace(0,1,50)

plt.plot(data)
plt.margins(0)
plt.show()

enter image description here

If your data does not range up to 1, it won't.

Same code with data = np.linspace(0,0.99,50) produces

enter image description here

So you need to set the limits manually to whatever range you want, because matplotlib cannot guess for you.

import matplotlib.pyplot as plt
import numpy as np

data = np.linspace(0,0.99,50)

plt.plot(data)
plt.margins(x=0)
plt.ylim(0,1)
plt.show()

enter image description here

Upvotes: 2

Related Questions