Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set axis to start from corner in Matplotlib [duplicate]

Tags:

matplotlib

this is a graph that I plotted:

# MatPlotlib
import matplotlib.pyplot as plt
# Scientific libraries
import numpy as np

plt.figure(1)

points = np.array([(100, 6.09),
                   (111, 8.42),
                   (119, 10.6),
                   (129, 12.5),
                   (139, 14.9),
                   (149, 17.2),
                   (200, 28.9),
                   (250, 40.9),
                   (299, 52.4),
                   (349, 64.7),
                   (400, 76.9)])

# get x and y vectors
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)
# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'bo', x_new, y_new)

plt.show()

enter image description here

I find that all the graphs I plot do not have their axes starting from the corner of the box, could anyone tell me how I can correct this? Aside from setting limits in the graph

like image 863
Tian Avatar asked Jun 05 '17 10:06

Tian


People also ask

How do I change the axis range in MatPlotLib?

MatPlotLib with Python To change the range of X and Y axes, we can use xlim() and ylim() methods.

What are the two ways to adjust axis limits of the plot using MatPlotLib?

To plot the graph, use the plot() function. To set the limit of the x-axis, use the xlim() function. To set the limit of the y-axis, use the ylim() function.

How do I create a twin axis in MatPlotLib?

Matplotlib twinx() and twiny() Function In the Axes Module, there is a function named Axes. twinx() function which is used to create a twin Axes that are sharing the x-axis. Similarly, the function twiny() is used to create a second x axis in your figure, which means twin axes sharing the y-axis.


1 Answers

By default, matplotlib adds a 5% margin on all sides of the axes. To get rid of that margin, you can use plt.margins(0).

import matplotlib.pyplot as plt

plt.plot([1,2,3],[1,2,3], marker="o")
plt.margins(0)
plt.show()

enter image description here

To change the margins for the complete script, you may use

plt.rcParams['axes.xmargin'] = 0
plt.rcParams['axes.ymargin'] = 0

Or you may change your rc file to include those settings.

like image 179
ImportanceOfBeingErnest Avatar answered Jan 04 '23 10:01

ImportanceOfBeingErnest