简体   繁体   中英

matplotlib: drawing a horizontal line spanning over multiple subplots, with interactive mode

I am using interactive mode in matplotlib to calculate some parameters. I want to plot two subplots horizontally, then draw a horizontal line that goes through both of them. I reproduced my problem as in the following code

import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np
plt.ion()
f,axarr=plt.subplots(1,2,sharey=True,gridspec_kw={'width_ratios':[100,1]})
axarr[0].set_title('subplot_1')
axarr[1].set_title('subplot_2')
axarr[0].get_xaxis().set_visible(False)
axarr[1].get_xaxis().set_visible(False)
for i in range(100):
    data_1 =np.random.randint(100,size=1)
    data_2=np.random.randint(100,size=1)
    axarr[0].bar(i,data_1,width=1)
    axarr[1].bar(1,data_2,width=1)
    axarr[0].axhline(y=data_2+5,xmin=0,xmax=i,c='yellow',linewidth=10,zorder=0,clip_on=False,animated=True)
    axarr[1].axhline(y=N_level+20,c='yellow',xmin=0,xmax=1,linewidth=10,zorder=0,clip_on=False,animated=True)
    plt.pause(0.000000000001)

But this code doesn't generate this horizontal line. I need to have a plot similar to this figure 在此处输入图片说明

You need to remove animated=True . This will show the line.

Now the problem is that you add a new line for each iteration step, such that at the end, the complete plot will be yellow. To avoid that, I would suggest to define the line outside the loop and only update its position for each step.

import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np
plt.ion()
f,axarr=plt.subplots(1,2,sharey=True,gridspec_kw={'width_ratios':[50,1]})
axarr[0].set_title('subplot_1')
axarr[1].set_title('subplot_2')
axarr[0].get_xaxis().set_visible(False)
axarr[1].get_xaxis().set_visible(False)

line = axarr[0].axhline(y=0,xmin=0,xmax=1,c='yellow',linewidth=2,zorder=5,clip_on=False)

for i in range(100):
    data_1 =np.random.randint(100,size=1)
    data_2=np.random.randint(100,size=1)
    axarr[0].bar(i,data_1,width=1)
    axarr[1].bar(1,data_2,width=1)
    line.set_ydata([data_1,data_1])
    plt.pause(0.000000000001)
plt.ioff()
plt.show()

Note that I left out the second line, because the variable is undefined in the code and I don't know what it should be showing.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM