[英]Why does color bars change the color in cycle drawing? (matplotlib)
每次繪制條形圖時,它們都會隨機改變顏色。 為什么? 它的原因是什么?
import matplotlib.pyplot as plt
from matplotlib import mlab
fig = plt.figure()
ax4 = fig.add_subplot(111)
ax4.set_xlim(-10,80)
ax4.set_ylim(0,30)
def view(ylist):
xmin = 0
xmax = 70.0
dx = 10
xlist = mlab.frange (xmin, xmax, dx)
ax4.bar(xlist, ylist, dx)
plt.pause(0.5)
plt.draw()
ylist = [0 for p in range(8)]
for i in range(10):
view(ylist)
ylist[0] +=1
ylist[3] +=2
plt.close()
在運行代碼時 - 條形正在循環改變顏色。 為什么? 問題是——怎么了?
問題是您正在繪制 10 個不同的條形圖,它們都在相同的軸上。 您的條形圖繪制在相同的 x 坐標處,因此繪制在彼此的頂部。 這仍然意味着您的其他條形仍然存在,因此 matplotlib 會循環繪制“新”條形的顏色。
你可以做兩件事。 首先,您可以調用plt.cla()
清除當前軸。 但是,這將重置您的 y 軸限制(這使它看起來沒有發生任何事情)。 這意味着您必須使用ax4.set_ylim(0,20)
設置 y 軸限制。
其次,您可以在ax4.bar()
指定您想要條形的顏色(盡管這仍在舊條形上繪制)。
import matplotlib.pyplot as plt
from matplotlib import mlab
fig = plt.figure()
ax4 = fig.add_subplot(111)
ax4.set_xlim(-10,80)
ax4.set_ylim(0,30)
def view(ylist):
xmin = 0
xmax = 70.0
dx = 10
xlist = mlab.frange (xmin, xmax, dx)
plt.cla()
ax4.set_ylim(0,20)
ax4.bar(xlist, ylist, dx) # can add color="blue" if you don't want to use plt.cla()
plt.pause(0.5)
plt.draw()
ylist = [0 for p in range(8)]
for i in range(10):
view(ylist)
ylist[0] +=1
ylist[3] +=2
plt.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.