使用 matplotlib 在最终图中裁剪出绘图区域
Plot area getting cropped out in the final graph using matplotlib
我正在尝试使用数据集中的最后 10 个数据点绘制连续图
from time import sleep
import matplotlib.pyplot as plt
#plt.ion()
ls1 = [0,0,0,0,0,0,0,0,0,0]
l1,= plt.plot([])
a=[]
if 1:
count=4
while True:
x=count%4
count+=1
print x
ls1.append(x)
l1.set_data(range(10),ls1[-10:])
#ax.set_xlim(-2,12)?
#ax.set_ylim(0,5)? this throws error as ax is not defined and I am unable to define it
plt.draw()
plt.pause(0.5)
#plt.show()
sleep(0.5)
Output graph
如您所见,输出图的轴限制在 [-0.06,+0.06] 范围内,而我的输出具有 xlim=[0,10] 和 ylim=[0,4]。
我如何实施这些限制以获得正确的图表?
ax
通常指的是我们放置图的 Axe(s)
的变量。
fig, ax = plt.subplots()
#or:
ax = plt.gca()
您没有在代码中声明它。 Check here subplots()
方法。
要强制设置 x 和 y 边界,您可以执行以下任一操作:
fig, ax = plt.subplots()
ax.plot(range(10), ls1[-10:])
ax.set_xlim(0,10)
ax.set_ylim(0,4)
# ...
plt.show()
... 或:
plt.plot(range(10), ls1[-10:])
plt.xlim(0, 10)
plt.ylim(0, 4)
# ...
您可以定义图形,然后使用轴命令。这是一个可能的解决方案:
from time import sleep
import matplotlib.pyplot as plt
#plt.ion()
ls1 = [0,0,0,0,0,0,0,0,0,0]
fig = plt.figure() # define a Figure
ax = fig.gca() # get the ax
l1,= ax.plot([])
a=[]
if 1:
count=4
while True:
x=count%4
count+=1
print(x)
ls1.append(x)
l1.set_data(range(10),ls1[-10:])
ax.set_xlim(-2,12) # now ax is defined
ax.set_ylim(0,5)
plt.draw()
plt.show()
plt.pause(0.5)
sleep(0.5)
我正在尝试使用数据集中的最后 10 个数据点绘制连续图
from time import sleep
import matplotlib.pyplot as plt
#plt.ion()
ls1 = [0,0,0,0,0,0,0,0,0,0]
l1,= plt.plot([])
a=[]
if 1:
count=4
while True:
x=count%4
count+=1
print x
ls1.append(x)
l1.set_data(range(10),ls1[-10:])
#ax.set_xlim(-2,12)?
#ax.set_ylim(0,5)? this throws error as ax is not defined and I am unable to define it
plt.draw()
plt.pause(0.5)
#plt.show()
sleep(0.5)
Output graph 如您所见,输出图的轴限制在 [-0.06,+0.06] 范围内,而我的输出具有 xlim=[0,10] 和 ylim=[0,4]。 我如何实施这些限制以获得正确的图表?
ax
通常指的是我们放置图的 Axe(s)
的变量。
fig, ax = plt.subplots()
#or:
ax = plt.gca()
您没有在代码中声明它。 Check here subplots()
方法。
要强制设置 x 和 y 边界,您可以执行以下任一操作:
fig, ax = plt.subplots()
ax.plot(range(10), ls1[-10:])
ax.set_xlim(0,10)
ax.set_ylim(0,4)
# ...
plt.show()
... 或:
plt.plot(range(10), ls1[-10:])
plt.xlim(0, 10)
plt.ylim(0, 4)
# ...
您可以定义图形,然后使用轴命令。这是一个可能的解决方案:
from time import sleep
import matplotlib.pyplot as plt
#plt.ion()
ls1 = [0,0,0,0,0,0,0,0,0,0]
fig = plt.figure() # define a Figure
ax = fig.gca() # get the ax
l1,= ax.plot([])
a=[]
if 1:
count=4
while True:
x=count%4
count+=1
print(x)
ls1.append(x)
l1.set_data(range(10),ls1[-10:])
ax.set_xlim(-2,12) # now ax is defined
ax.set_ylim(0,5)
plt.draw()
plt.show()
plt.pause(0.5)
sleep(0.5)