如何防止堆积重复图?

时间:2017-03-03 21:36:14

标签: matplotlib space subplot data-science

我有一个代码应该生成两个不同的图形并将它们放在一个图像中,并且无法弄清楚为什么它返回最后一次提到的图形两次。代码如下:

import spacepy as sp
from spacepy import pycdf
from pylab import *
from spacepy.toolbox import windowMean, normalize
from spacepy.plot.utils import annotate_xaxis
import pylab
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
import matplotlib.ticker as ticker
from matplotlib.colors import LogNorm
from matplotlib.ticker import LogLocator
from matplotlib.dates import DateFormatter
from matplotlib.dates import DayLocator, HourLocator, MinuteLocator
from matplotlib import rc, rcParams
import matplotlib.dates as mdates
import datetime as dt
import bisect as bi
import seaborn as sea
import sys
import os
import multilabel as ml
import pandas as pd

sea.set_context('poster')
# sea.set_style('ticks',{'axes.facecolor':'yellow'})
sea.set_style('whitegrid')
sea.set_palette('muted',color_codes=True)
rc('text', usetex=True)
rc('font', family='Mono')
rcParams['text.latex.preamble']=[r'\usepackage{amsmath}']

MMS_1_HPCA_SURVEY_ION = pycdf.CDF(r'/home/ary/Desktop/Arya/Project/Data/MMS/1/HPCA/Survey/Ion/mms1_hpca_srvy_l2_ion_20151025120000_v1.0.0.cdf')

EPOCH_SURVEY_ION_1 = MMS_1_HPCA_SURVEY_ION['Epoch'][...]
H_Flux_SURVEY_ION_1 = MMS_1_HPCA_SURVEY_ION['mms1_hpca_hplus_flux'][...]
O_Flux_SURVEY_ION_1 = MMS_1_HPCA_SURVEY_ION['mms1_hpca_oplus_flux'][...]
Ion_Energy_SURVEY_ION_1 = MMS_1_HPCA_SURVEY_ION['mms1_hpca_ion_energy'][...]

MMS_SURVEY_ION_1_Start_time = dt.datetime(2015, 10, 25, 12, 0, 0, 908117)
MMS_SURVEY_ION_1_Finish_time = dt.datetime(2015, 10, 25, 16, 22, 24, 403623)

dt_MMS = dt.timedelta(seconds = 15)

plt.close('all')

fig_MMS, axs_MMS = plt.subplots(2,sharex=True)
cmap = plt.get_cmap(cm.jet)
cmap.set_bad('black')

sidx_MMS_1_SURVEY_ION = bi.bisect_left(EPOCH_SURVEY_ION_1,MMS_SURVEY_ION_1_Start_time)
sidx_MMS_1_SURVEY_ION = int(sidx_MMS_1_SURVEY_ION-(sidx_MMS_1_SURVEY_ION/100))
lidx_MMS_1_SURVEY_ION = bi.bisect_left(EPOCH_SURVEY_ION_1, MMS_SURVEY_ION_1_Finish_time)
lidx_MMS_1_SURVEY_ION = int(lidx_MMS_1_SURVEY_ION+((len(EPOCH_SURVEY_ION_1)-lidx_MMS_1_SURVEY_ION)/100))

if MMS_SURVEY_ION_1_Start_time.date() == MMS_SURVEY_ION_1_Finish_time.date():
    stopfmt = '%H:%M'
else:
    stopfmt = '%-m/%-d/%y %H:%M'

title_1 = MMS_SURVEY_ION_1_Start_time.strftime('%m/%d/%y %H:%M')+' -'+MMS_SURVEY_ION_1_Finish_time.strftime(stopfmt)

if dt_MMS.seconds !=0:
    title_1 = title_1 + ' with '+str(dt_MMS.seconds)+' second time averaging'

for j, ax in enumerate(axs_MMS.T.flatten()):
    flix_1 = np.array(H_Flux_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION, 
                                          j, :].T)

    if dt_MMS==dt.timedelta(0):
        fluxwin_1 = flix_1
        timewin_1 = EPOCH_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION]
    else:
        fluxwin_1=[[0 for y in range(len(flix_1))] for x_1 in range(len(flix_1))]
        for i, flox in enumerate(flix_1):
            fluxwin_1[i], timewin_1 = windowMean(flox, EPOCH_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION],
                                                 winsize=dt_MMS, overlap=dt.timedelta(0))
            fluxwin_1[i] = np.array(fluxwin_1[i])
            for x_1 in np.where(np.diff(EPOCH_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION])
                    >dt.timedelta(hours=1))[0]+sidx_MMS_1_SURVEY_ION:
                fluxwin_1[i][bi.bisect_right(timewin_1, EPOCH_SURVEY_ION_1[x_1]):bi.bisect_right(timewin_1, 
                                                                                               EPOCH_SURVEY_ION_1[x_1+1])]=0
        fluxwin_1 = np.array(fluxwin_1)

    fluxwin_1[np.where(fluxwin_1<=0)] = 0

    x_1 = mdates.date2num(timewin_1)

    pax_1 = ax.pcolormesh(x_1, Ion_Energy_SURVEY_ION_1, fluxwin_1, shading='turkey',cmap=cmap, vmin=1, 
                          vmax=np.nanmax(H_Flux_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION,:,:]), 
                          norm=LogNorm())

    sax_1 = ax.twinx()
    plt.setp(sax_1.get_yticklabels(), visible=False)
    sax_1.tick_params(axis='y', right='off')
    ax.set_xlim(MMS_SURVEY_ION_1_Start_time, MMS_SURVEY_ION_1_Finish_time)
    ax.set_yscale('log')
    ax.set_yticks([10, 100, 1000,10000])
    #Allows non-log formatted values to be used for ticks
    ax.yaxis.set_major_formatter(plt.ScalarFormatter())

axs_MMS[0].set_ylabel('Energy (eV)')
axs_MMS[0].set_title(title_1)

for j, ax in enumerate(axs_MMS.T.flatten()):
    flix_2 = np.array(O_Flux_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION, 
                                          j, :].T)

    if dt_MMS==dt.timedelta(0):
        fluxwin_2 = flix_2
        timewin_2 = EPOCH_SURVEY_ION_2[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION]
    else:
        fluxwin_2=[[0 for y in range(len(flix_2))] for x_2 in range(len(flix_2))]
        for i, flox in enumerate(flix_2):
            fluxwin_2[i], timewin_2 = windowMean(flox, EPOCH_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION],
                                                 winsize=dt_MMS, overlap=dt.timedelta(0))
            fluxwin_2[i] = np.array(fluxwin_2[i])
            for x_2 in np.where(np.diff(EPOCH_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION])
                    >dt.timedelta(hours=1))[0]+sidx_MMS_1_SURVEY_ION:
                fluxwin_2[i][bi.bisect_right(timewin_2, EPOCH_SURVEY_ION_1[x_2]):bi.bisect_right(timewin_2, 
                                                                                               EPOCH_SURVEY_ION_1[x_1+1])]=0
        fluxwin_2 = np.array(fluxwin_2)

    fluxwin_2[np.where(fluxwin_2<=0)] = 0

    x_2 = mdates.date2num(timewin_2)

    pax_2 = ax.pcolormesh(x_2, Ion_Energy_SURVEY_ION_1, fluxwin_2, shading='turkey',cmap=cmap, vmin=1, 
                          vmax=np.nanmax(O_Flux_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION,:,:]), 
                          norm=LogNorm())

    sax_2 = ax.twinx()
    plt.setp(sax_2.get_yticklabels(), visible=False)
    sax_2.tick_params(axis='y', right='off')
    ax.set_xlim(MMS_SURVEY_ION_1_Start_time, MMS_SURVEY_ION_1_Finish_time)
    ax.set_yscale('log')
    ax.set_yticks([10, 100, 1000,10000])
    #Allows non-log formatted values to be used for ticks
    ax.yaxis.set_major_formatter(plt.ScalarFormatter())

axs_MMS[1].set_ylabel('Energy (eV)')

cbar_ax_1 = fig_MMS.add_axes([0.93, 0.15, 0.02, 0.7])

cb_MMS_1 = fig_MMS.colorbar(pax_1, cax=cbar_ax_1)
cb_MMS_1.set_label(r'Counts sec$^{-1}$ ster$^{-1}$ cm$^{-2}$ keV$^{-1}$')
#Sets the colorbar value range
cb_MMS_1.set_clim(1, np.nanmax(H_Flux_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION,:,:]))
#Redraws the colorbar
cb_MMS_1.draw_all()

,返回的图像如下:

enter image description here

1 个答案:

答案 0 :(得分:0)

请考虑以下与您的代码对应的示例:

function askquestion_dialog(fnopen)
    {

    return $("#new_question").dialog({
             dialogClass: 'new_question',
             position: ['center', 70],
             autoOpen:false,
             modal:true,
             width:710,
             height:640,
             resizable:false,
             open: fnopen,
             close: function(event) {   
                 /*if(!$(event.currentTarget).hasClass('ui-dialog-titlebar-close')) {
                        load_question(questionid);
                 }*/
                $(this).find("#form_question").trigger('reset');
                $(this).find("#tags_choose").trigger("chosen:updated");
                $(this).dialog('destroy');
            }
        });
    }

enter image description here

在此绘制两个轴的每个图。

相反,您需要绘制到不同的轴:

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2,sharex=True, figsize=(4,2.4))

for j, ax in enumerate(axs.T.flatten()):
    x_1 = [[0,1,2],[0,1,2],[0,1,2]]
    y_1 = [[0,0,0],[1,1,1],[2,2,2]]
    z_1 = [[6,5,4],[2,3,4],[6,5,4]]

    pax_1 = ax.pcolormesh(x_1, y_1, z_1)

axs[0].set_ylabel('Energy (eV)')
axs[0].set_title("Title1")

for j, ax in enumerate(axs.T.flatten()):
    x_2 = [[3,4,5],[3,4,5],[3,4,5]]
    y_2 = [[0,0,0],[1,1,1],[2,2,2]]
    z_2 = [[2,1,2],[2,1,2],[2,1,2]]

    pax_2 = ax.pcolormesh(x_2, y_2, z_2)

axs[1].set_ylabel('Energy (eV)')
plt.show()

enter image description here