问题
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)
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.
回答1:
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)
回答2:
Alternatively:
x = np.linspace(0,5,11)
plt.xlim((0,5))
plt.ylim((0,25))
plt.plot(x,x**2);
回答3:
To not have borders you can use set_xlim and set_ylim:
ax.set_xlim([0, 5])
ax.set_ylim([0, 25])
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()
来源:https://stackoverflow.com/questions/59786528/why-is-there-unnecessary-whitespace-while-plotting-figures-with-pandas-matplotl