准确指定要从matplotlib图中删除的行

时间:2018-04-24 16:55:13

标签: python matplotlib

我正在创建一个界面,我有一些“清除此”和“清除”按钮以删除绘图的各种元素。

matplotlib的问题在于我必须知道绘制对象的确切顺序,以便用ax.lines.pop()删除正确的对象。例如,绘图可以包含原始数据,然后是平滑版本,然后是顶部适合,但根据调用的顺序,ax.lines.pop(2)将删除蓝线或红线。

但我怎样才能不断删除,例如多层场景中的红线?

enter image description here

import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import medfilt

a = np.random.normal(0, 1, 100)
b = medfilt(a, 17)

fig1, axes = plt.subplots(ncols = 2)

ax1, ax2 = axes

ax1.set_title("Figure 1")
ax1.plot(a, color = "darkgrey")  # 0
ax1.plot(b, color = "firebrick") # 1
ax1.axhline(0.5, color = "blue") # 2

ax1.lines.pop(2)

ax2.set_title("Figure 2")
ax2.plot(a, color = "darkgrey")  # 0
ax2.axhline(0.5, color = "blue") # 2
ax2.plot(b, color = "firebrick") # 1

ax2.lines.pop(2)

plt.show()

1 个答案:

答案 0 :(得分:1)

为了清晰和简洁的说明,以下示例绘制单个图形,而不是删除该行,它切换其可见性。请注意,其中两行显式标记,第三行默认为其分配标签。我们使用这些标签来指明我们的路线。

如果你真的想要删除该行,只需用你对pop(),c.f的调用替换对set_visible()的调用。 ax.lines.pop(n)的

import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons

import numpy as np
from scipy.signal import medfilt

a = np.random.normal(0, 1, 100)
b = medfilt(a, 17)

fig = plt.figure()
ax  = fig.add_subplot(1,1,1)

# Create a graph with two curves, and save the lines
ax.set_title("Figure 1")
ax.plot(a, label='a', color = "darkgrey")  # 0
ax.plot(b, label='b', color = "firebrick") # 1
ax.axhline(0.5, color = "blue") # 2

# Show the labels
plt.legend()

# Labels and initial states for buttons
labels = []
states = []
for l in ax.lines:
    labels.append( l.get_label() )
    states.append( l.get_visible() )

# Add a box with checkbuttons
plt.subplots_adjust(right=0.8)
bx = plt.axes( [0.85,0.4,0.1,0.15] )
cb = CheckButtons( bx, labels, states )

# Function to toggle visibility of each line
def toggle( label ):
    n = labels.index(label)
    ax.lines[ n ].set_visible( not ax.lines[ n ].get_visible() )
    plt.draw()

# Connect the function to the buttons
cb.on_clicked( toggle )

# And start the show
plt.show()