2

I would like to extend solution of the question "How to keep some text relative to the line into the plot when the plot changes" with two subplots controlled with a pair of widget sliders.

The code I have tried it makes no errors, but it does not show the Figure nor the controls.

from ipywidgets import widgets
from IPython.display import display
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

fig1, ax1 = plt.subplots(211)
line1, = ax1.semilogx([],[], label='Multipath')
hline1 = ax1.axhline(y = 0, linewidth=1.2, color='black',ls='--')
text1 = ax1.text(0, 0, "T Threshold",
                verticalalignment='top', horizontalalignment='left',
                transform=ax1.get_yaxis_transform(),
                color='brown', fontsize=10)
ax1.set_xlabel('Separation Distance, r (m)')
ax1.set_ylabel('Received Power, $P_t$ (dBm)')
ax1.grid(True,which="both",ls=":")
ax1.legend()

fig2, ax2 = plt.subplots(212)
line2, = ax2.semilogx([],[], label='Monostatic Link')
hline2 = ax2.axhline(y = 0, linewidth=1.2, color='black',ls='--')
text2 = ax2.text(0, 0, "R Threshold",
                verticalalignment='top', horizontalalignment='left',
                transform=ax2.get_yaxis_transform(),
                color='brown', fontsize=10)
ax2.set_xlabel('Separation Distance, r (m)')
ax2.set_ylabel('Received Power, $P_t$ (dBm)')
ax2.grid(True,which="both",ls=":")
ax2.legend()

def update_plot(h1, h2):
    D = np.arange(0.5, 12.0, 0.0100)
    r = np.sqrt((h1-h2)**2 + D**2)
    freq = 865.7 #freq = 915 MHz
    lmb = 300/freq 
    H = D**2/(D**2+2*h1*h2)
    theta = 4*np.pi*h1*h2/(lmb*D)
    q_e = H**2*(np.sin(theta))**2 + (1 - H*np.cos(theta))**2
    q_e_rcn1 = 1
    P_x_G = 4 # 4 Watt EIRP
    sigma = 1.94
    N_1 = np.random.normal(0,sigma,D.shape)
    rnd = 10**(-N_1/10)
    F = 10
    y = 10*np.log10( 1000*(P_x_G*1.622*((lmb)**2) *0.5*1) / (((4*np.pi*r)**2) *1.2*1*F)*q_e*rnd*q_e_rcn1 )
    line1.set_data(r,y)

    hline1.set_ydata(-18)
    text1.set_position((0.02, -18.5))
    ax1.relim()
    ax1.autoscale_view()
    fig1.canvas.draw_idle()
    ######################################
    rd =np.sqrt((h1-h2)**2 + D**2)
    rd = np.sort(rd)
    P_r=0.8
    G_r=5 # 7dBi
    q_e_rcn2 = 1
    N_2 = np.random.normal(0, sigma*2, D.shape)
    rnd_2 = 10**(-N_2/10)
    F_2 = 126 # 21 dB for K=3dB and P_outage = 0.05
    y = 10*np.log10(  1000*(P_r*(G_r*1.622)**2*(lmb)**4*0.5**2*0.25)/((4*np.pi*rd)**4*1.2**2*1**2*F_2)*
            q_e**2*rnd*rnd_2*q_e_rcn1*q_e_rcn2  )
    line2.set_data(rd,y)
    hline2.set_ydata(-80)
    text2.set_position((0.02, -80.5))
    ax2.relim()
    ax2.autoscale_view()
    fig2.canvas.draw_idle()

r_height = widgets.FloatSlider(min=0.5, max=4, value=0.9, description= 'R_Height:')
t_height = widgets.FloatSlider(min=0.15, max=1.5, value=0.5, description= 'T_Height:')
widgets.interactive(update_plot, h1=r_height, h2=t_height)

In the second subplot, there would be a horizontal line at y=-80 with a text that should move in a similar way as the first subplot of the figure.

How could I add the second subplot using the same controls?

Regards.

Community
  • 1
  • 1
user1993416
  • 698
  • 1
  • 9
  • 28

1 Answers1

2

This code does produce an error. The problem is that you are creating a figure with 211 (i.e. twohundredeleven) subplots. Those are stored in an array called ax1 and this array does not have a .semilogx method. Hence the error AttributeError: 'numpy.ndarray' object has no attribute 'semilogx'.

So, what you need instead is only two subplots, which you may directly unpack.

fig, (ax1, ax2) = plt.subplots(nrows=2)

The rest is basically adjusting the code for the new situation. It should then look like this:

from ipywidgets import widgets
from IPython.display import display
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

fig, (ax1, ax2) = plt.subplots(nrows=2)
line1, = ax1.semilogx([],[], label='Multipath')
hline1 = ax1.axhline(y = 0, linewidth=1.2, color='black',ls='--')
text1 = ax1.text(0, 0, "T Threshold",
                verticalalignment='top', horizontalalignment='left',
                transform=ax1.get_yaxis_transform(),
                color='brown', fontsize=10)
ax1.set_xlabel('Separation Distance, r (m)')
ax1.set_ylabel('Received Power, $P_t$ (dBm)')
ax1.grid(True,which="both",ls=":")
ax1.legend()

line2, = ax2.semilogx([],[], label='Monostatic Link')
hline2 = ax2.axhline(y = 0, linewidth=1.2, color='black',ls='--')
text2 = ax2.text(0, 0, "R Threshold",
                verticalalignment='top', horizontalalignment='left',
                transform=ax2.get_yaxis_transform(),
                color='brown', fontsize=10)
ax2.set_xlabel('Separation Distance, r (m)')
ax2.set_ylabel('Received Power, $P_t$ (dBm)')
ax2.grid(True,which="both",ls=":")
ax2.legend()

def update_plot(h1, h2):
    D = np.arange(0.5, 12.0, 0.0100)
    r = np.sqrt((h1-h2)**2 + D**2)
    freq = 865.7 #freq = 915 MHz
    lmb = 300/freq 
    H = D**2/(D**2+2*h1*h2)
    theta = 4*np.pi*h1*h2/(lmb*D)
    q_e = H**2*(np.sin(theta))**2 + (1 - H*np.cos(theta))**2
    q_e_rcn1 = 1
    P_x_G = 4 # 4 Watt EIRP
    sigma = 1.94
    N_1 = np.random.normal(0,sigma,D.shape)
    rnd = 10**(-N_1/10)
    F = 10
    y = 10*np.log10( 1000*(P_x_G*1.622*((lmb)**2) *0.5*1) / (((4*np.pi*r)**2) *1.2*1*F)*q_e*rnd*q_e_rcn1 )
    line1.set_data(r,y)

    hline1.set_ydata(-18)
    text1.set_position((0.02, -18.5))
    ax1.relim()
    ax1.autoscale_view()

    ######################################
    rd =np.sqrt((h1-h2)**2 + D**2)
    rd = np.sort(rd)
    P_r=0.8
    G_r=5 # 7dBi
    q_e_rcn2 = 1
    N_2 = np.random.normal(0, sigma*2, D.shape)
    rnd_2 = 10**(-N_2/10)
    F_2 = 126 # 21 dB for K=3dB and P_outage = 0.05
    y = 10*np.log10(  1000*(P_r*(G_r*1.622)**2*(lmb)**4*0.5**2*0.25)/((4*np.pi*rd)**4*1.2**2*1**2*F_2)*
            q_e**2*rnd*rnd_2*q_e_rcn1*q_e_rcn2  )
    line2.set_data(rd,y)
    hline2.set_ydata(-80)
    text2.set_position((0.02, -80.5))
    ax2.relim()
    ax2.autoscale_view()

    fig.canvas.draw_idle()

r_height = widgets.FloatSlider(min=0.5, max=4, value=0.9, description= 'R_Height:')
t_height = widgets.FloatSlider(min=0.15, max=1.5, value=0.5, description= 'T_Height:')
widgets.interactive(update_plot, h1=r_height, h2=t_height)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Thank you. The plot seamlessly updates with the controls. I would like to ask you as a final question how could I convert one of the subplots from semilogx to scatter plot? I have tried to change `semilogx` for `scatter`but give error as scatter is not iterable. – user1993416 Jul 12 '18 at 09:14
  • it says "'PathCollection' object is not iterable" and if I take out the comma after `line2` for example (is scatter is the second subplot) then the error is "AttributeError: 'PathCollection' object has no attribute 'set_data'" and points to line `line2.set_data(rd,y)`. – user1993416 Jul 12 '18 at 09:21
  • That is really a different question.. that for sure has an answer elsewhere, if you google for "matplotlib update scatter". – ImportanceOfBeingErnest Jul 12 '18 at 09:40
  • You are right. I have searched but found only answer referred to offset in animations with scatter plots. – user1993416 Jul 12 '18 at 09:43
  • See e.g. [here](https://stackoverflow.com/questions/42722691/python-matplotlib-update-scatter-plot-from-a-function). – ImportanceOfBeingErnest Jul 12 '18 at 09:45
  • It works. However, if I take semilog x-scale with `ax2.set_xscale('log')` the plot does not work. – user1993416 Jul 12 '18 at 10:04