Две фигуры одновременно в Python - PullRequest
0 голосов
/ 13 мая 2018

У меня есть код, который запускает две цифры, по одному или одновременно.Проблема в том, когда они работают одновременно.Они оба не показаны правильно.Я пытался использовать plt.subplotlib, но это не помогло.вот код

import numpy as np
import matplotlib.pyplot as plt

Choice = input('Which figure do you want to run: \n *for Fig.1 , write 1 \n *for Fig.2, write 2 \n *for both , write b \n--> ')  
Etta_Source={};Etta_Source1={};QKN_Source={}

for E_So in [100,200,400,800,600,1000]:
    for Temp in range(0,110,10):
        Etta = 0.8 - ((3.41*Temp)+(0.014*(Temp)**2))/E_So
        if Choice == '1' or Choice == 'b':
            QKN_Source[Temp] = Etta*2.3*E_So
        Etta_Source[Temp] = Etta
        if E_So == 1000 and (Choice == '2' or Choice == 'b'):
            Etta_Source1[Temp]=Etta
    if Choice == '1' or Choice == 'b':
        plt.figure(1)
        plt.plot(QKN_Source.keys(),QKN_Source.values(),label='D = %s'%E_So)
        QKN_Source.clear()
    if Choice == '2' or Choice == 'b':
        plt.figure(2)
        plt.plot(Etta_Source.keys(),Etta_Source.values(),label='C= %s'%E_So)
        Etta_Source.clear()

if Choice == '2' or Choice == 'b':
    plt.axhline(0.8,ls='-.',color='skyblue')
    plt.fill_between(Etta_Source1.keys(),Etta_Source1.values(),0.8,facecolor='wheat') 
    plt.axhspan(0.8,1.0,alpha=0.5, color='c')
    plt.axis([0,100,0,1])
    plt.text(50, 0.9, r'Area 1',fontsize=14,fontweight='bold')
    plt.text(80, 0.6, r'Area 2',fontsize=14,fontweight='bold')
    plt.yticks(np.arange(0,1.1,0.1))
    plt.ylabel('W',fontsize=14)
if Choice == '1' or Choice == 'b':
    plt.axis([0,100,0,2000]) 
    plt.ylabel('V',fontsize=14)

plt.grid(True)   
plt.title('Results',color='black',fontsize=15,fontweight='bold')
plt.xticks(range(0,110,10),fontsize=14)
plt.xlabel(r'$\beta_a +  \alpha_a$',fontsize=14)
plt.tight_layout()
plt.legend(loc=1)
plt.show()

Неправильные цифры: enter image description here

цифры должны выглядеть так, когда они оба работают enter image description here

1 Ответ

0 голосов
/ 13 мая 2018

Как указано в комментариях, вы не указываете объект оси , поэтому plt.XYZ просто берет последний объект для выполнения функции.Способ преодолеть эту проблему - сохранить каждый объект оси в переменной, чтобы вы могли обращаться к ним отдельно.Вот пример, максимально приближенный к вашему коду:

import numpy as np
import matplotlib.pyplot as plt

Choice = input('Which figure do you want to run: \n *for Fig.1 , write 1 \n *for Fig.2, write 2 \n *for both , write b \n--> ')  
Etta_Source={};Etta_Source1={};QKN_Source={}

for E_So in [100,200,400,800,600,1000]:
    for Temp in range(0,110,10):
        Etta = 0.8 - ((3.41*Temp)+(0.014*(Temp)**2))/E_So
        if Choice == '1' or Choice == 'b':
            QKN_Source[Temp] = Etta*2.3*E_So
        Etta_Source[Temp] = Etta
        if E_So == 1000 and (Choice == '2' or Choice == 'b'):
            Etta_Source1[Temp]=Etta
    if Choice == '1' or Choice == 'b':
        fig1 = plt.figure(1)
        #get axis object for this figure
        ax1 = plt.gca()
        #now perform all commands with this axis object 
        ax1.plot(QKN_Source.keys(),QKN_Source.values(),label='D = %s'%E_So)
        QKN_Source.clear()
    if Choice == '2' or Choice == 'b':
        fig2 = plt.figure(2)
        #and create a separate axis object for the second figure
        ax2 = plt.gca()
        ax2.plot(Etta_Source.keys(),Etta_Source.values(),label='C= %s'%E_So)
        Etta_Source.clear()

axlist = [] #collect the axes for the choices
if Choice == '2' or Choice == 'b':
    ax2.axhline(0.8,ls='-.',color='skyblue')
    ax2.fill_between(Etta_Source1.keys(),Etta_Source1.values(),0.8,facecolor='wheat') 
    ax2.axhspan(0.8,1.0,alpha=0.5, color='c')
    ax2.axis([0,100,0,1])
    ax2.text(50, 0.9, r'Area 1',fontsize=14,fontweight='bold')
    ax2.text(80, 0.6, r'Area 2',fontsize=14,fontweight='bold')
    ax2.set_yticks(np.arange(0,1.1,0.1))
    ax2.set_ylabel('W',fontsize=14)
    axlist.append(ax2)
if Choice == '1' or Choice == 'b':
    ax1.axis([0,100,0,2000]) 
    ax1.set_ylabel('V',fontsize=14)
    axlist.append(ax1)

#now we have to apply these commands to both axis objects, i.e., both figures
for ax in axlist:
    ax.grid(True) 
    ax.set_title('Results',color='black',fontsize=15,fontweight='bold')
    ax.set_xticks(range(0,110,10))
    ax.set_xlabel(r'$\beta_a +  \alpha_a$',fontsize=14)
    ax.legend(loc=1)
plt.show()

И так как вы упомянули, что пытались использовать вспомогательные участки - они возвращают объект оси , который мы можем сохранить и перезаписать-использовать позже.

...