-1

Whenever I plot figures using matplotlib or seaborn, there is always some whitespace remaining at the sides of the plot and the top and bottom of the plot. The (x_0,y_0) is not in the bottom left corner, x_0 is offset a little bit to the right and y_0 is offset a little bit upwards for some reason? I will demonstrate a quick example below with the 'ggplot' style so it is clear what I mean:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')

fig = plt.figure()
x = np.linspace(0,5,11)
ax = fig.add_axes([0.1,0.1,1,1])
ax.plot(x,x**2)

enter image description here

How do I get (0,0) to the bottom left corner and how do I get rid of the unnecessary space where y > 25, x >5?

Thank you.

the man
  • 1,131
  • 1
  • 8
  • 19

3 Answers3

4

The "whitespace" is caused by the plot margins. A better way to get rid of them without changing the axes limits explicitly is to set 0-margins

plt.style.use('ggplot')

fig = plt.figure()
x = np.linspace(0,5,11)
ax = fig.add_axes([0.1,0.1,1,1])
ax.margins(x=0,y=0)
ax.plot(x,x**2)

enter image description here

Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75
2

To not have borders you can use set_xlim and set_ylim:

ax.set_xlim([0, 5])
ax.set_ylim([0, 25])

enter image description here

Full code:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')

fig = plt.figure()
x = np.linspace(0,5,11)
ax = fig.add_axes([0.1,0.1,1,1])
ax.plot(x,x**2)
ax.set_xlim([0, 5])
ax.set_ylim([0, 25])
plt.show()
Joe
  • 12,057
  • 5
  • 39
  • 55
  • Ok, I see how this works in this specific example, but I get the same kind of problem when I create figures like boxplots using seaborn, how would I fix it in that case? – the man Jan 17 '20 at 12:15
2

Alternatively:

x = np.linspace(0,5,11)
plt.xlim((0,5))
plt.ylim((0,25))
plt.plot(x,x**2);

enter image description here

Sergey Bushmanov
  • 23,310
  • 7
  • 53
  • 72