Creating an insert in matplot lib

I created a plot in matplot lib and I want to add an insert to it. The data that I want to build is stored inside the dictionary, which I use in other figures. I find this data inside a loop, which then runs this loop again for a subtitle. Here is the relevant segment:

leg = [] colors=['red','blue'] count = 0 for key in Xpr: #Xpr holds my data #skipping over what I don't want to plot if not key[0] == '5': continue if key[1] == '0': continue if key[1] == 'a': continue leg.append(key) x = Xpr[key] y = Ypr[key] #Ypr holds the Y axis and is created when Xpr is created plt.scatter(x,y,color=colors[count],marker='.') count += 1 plt.xlabel(r'$z/\mu$') plt.ylabel(r'$\rho(z)$') plt.legend(leg) plt.xlim(0,10) #Now I wish to create the inset a=plt.axes([0.7,0.7,0.8,0.8]) count = 0 for key in Xpr: break if not key[0] == '5': continue if key[1] == '0': continue if key[1] == 'a': continue leg.append(key) x = Xpr[key] y = Ypr[key] a.plot(x,y,color=colors[count]) count += 1 plt.savefig('ion density 5per Un.pdf',format='pdf') plt.cla() 

The strange thing is that when I tried to move the insertion position, I still get the previous insertions (those that were from the previous code run). I even tried to comment out the line a=axes([]) without any visible phenomena. I am attaching an en example file. Why does he act this way? A figure of the crooked output

+4
source share
1 answer

The simple answer: you should use plt.clf() , which clears the shape, not the current axis. There is also a break in the insert loop, which means that none of these codes will ever be executed.

When you start doing more complex things than using single axes, you should switch to using the OO interface on matplotlib . This may seem more complicated at first, but you no longer need to worry about the hidden state of pyplot . Your code can be rewritten as

 fig = plt.figure() ax = fig.add_axes([.1,.1,.8,.8]) # main axes colors=['red','blue'] for key in Xpr: #Xpr holds my data #skipping over what I don't want to plot if not key[0] == '5': continue if key[1] == '0': continue if key[1] == 'a': continue x = Xpr[key] y = Ypr[key] #Ypr holds the Y axis and is created when Xpr is created ax.scatter(x,y,color=colors[count],marker='.',label=key) count += 1 ax.set_xlabel(r'$z/\mu$') ax.set_ylabel(r'$\rho(z)$') ax.set_xlim(0,10) leg = ax.legend() #Now I wish to create the inset ax_inset=fig.add_axes([0.7,0.7,0.3,0.3]) count =0 for key in Xpr: #Xpr holds my data if not key[0] == '5': continue if key[1] == '0': continue if key[1] == 'a': continue x = Xpr[key] y = Ypr[key] ax_inset.plot(x,y,color=colors[count],label=key) count +=1 ax_inset.legend() 
+3
source

Source: https://habr.com/ru/post/1433044/


All Articles