x = np.linspace(2000.0, 2018.0, num = 18)
for i in range(len(x)):
x[i]=int(x[i])
for i in range(2000, 2018):
y.append(dic[str(i)])
fig, ax = plt.subplots()
ax.plot(x, y, marker='o', color='r')
# set title
# set label for x
# set label for y
print(ax.get_xlim())
return ax
I am trying to plot a 18 points where x limit should be from (2000.0) to (2018.0). Some codes are hidden, but I just posted the critical parts. When I print the result out, the xlimit is
(1999.0999999999999, 2018.9000000000001)
not
(2000.0, 2018.0)
Please tell me what I am doing wrong.
You are not doing anything wrong; but you may have the wrong expectation concerning the limits of the plot.
By default, matplotlib leaves 5% margin on each side of the plot. Hence, if your data is in the range [x.min(), x.max()] == [2000.0, 2018.0]
your limits will be
[x.min()-0.05*(x.max()-x.min()), x.max()+0.05*(x.max()-x.min())] == [1999.1, 2018.9]
If you don't want to have any padding around your data, use ax.margins(x=0)
. In that case print(ax.get_xlim())
will print (2000.0, 2018.0)
Complete example:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(2000.0, 2018.0, num = 19)
y = np.cumsum(np.random.rand(len(x)))
x = x.astype(int)
fig, ax = plt.subplots()
ax.plot(x, y, marker='o', color='r')
ax.margins(x=0)
print(ax.get_xlim())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.