Пример #1
0
 def set_default_locators_and_formatters(self, axis):
     """
     Set the locators and formatters to specialized versions for
     log scaling.
     """
     axis.set_major_locator(AutoLocator())
     axis.set_major_formatter(ScalarFormatter())
     axis.set_minor_locator(NullLocator())
     axis.set_minor_formatter(NullFormatter())
Пример #2
0
 def set_default_locators_and_formatters(self, axis):
     """
     Set the locators and formatters to reasonable defaults for
     linear scaling.
     """
     axis.set_major_locator(AutoLocator())
     axis.set_major_formatter(ScalarFormatter())
     axis.set_minor_locator(NullLocator())
     axis.set_minor_formatter(NullFormatter())
Пример #3
0
def format_axis_with_grid(ax, x_label=None, y_label=None, x_rotation=False):
    """
    Adds a major and minor grid to axes, adds labels.

    Parameters
    ----------
    ax : Axes
        Axes object containing the figure axis (modified)
    x_label : str
        X axis label
    y_label : str
        Y axis label
    x_rotation : bool
        True rotates the X axis labels by 90 deg (useful for ISOT dates)


    Returns
    -------
    Axes
        Axes object containing the figure axis (modified)
    """

    # Change major ticks
    ax.xaxis.set_major_locator(AutoLocator())
    ax.yaxis.set_major_locator(AutoLocator())

    # Change minor ticks to show with divisor of 4
    ax.xaxis.set_minor_locator(AutoMinorLocator(4))
    ax.yaxis.set_minor_locator(AutoMinorLocator(4))
    ax.grid(which="major", color="#CCCCCC", linestyle="--")
    ax.grid(which="minor", color="#CCCCCC", linestyle=":")

    # Set axis labels
    if x_label:
        ax.set_xlabel(x_label)

    if y_label:
        ax.set_ylabel(y_label)

    # Rotate x axis labels
    if x_rotation:
        ax.tick_params(axis="x", labelrotation=90)

    return ax
Пример #4
0
def add_subplot_unshare(ax):
    ''' based on an answer from stacked overflow 
	'''
    ax._shared_x_axes.remove(ax)
    ax.xaxis.major = mpl.axis.Ticker()
    xloc = AutoLocator()
    xfmt = ScalarFormatter()
    ax.xaxis.set_major_locator(xloc)
    ax.xaxis.set_major_formatter(xfmt)
    ax.yaxis.set_tick_params(which='both', labelleft=True)
Пример #5
0
    def _get_locators(self, locator, at, upto, count, every, between, minor):

        log_base, symlog_thresh = self._parse_for_log_params(self.trans)

        if locator is not None:
            major_locator = locator

        elif upto is not None:
            if log_base:
                major_locator = LogLocator(base=log_base, numticks=upto)
            else:
                major_locator = MaxNLocator(upto, steps=[1, 1.5, 2, 2.5, 3, 5, 10])

        elif count is not None:
            if between is None:
                # This is rarely useful (unless you are setting limits)
                major_locator = LinearLocator(count)
            else:
                if log_base or symlog_thresh:
                    forward, inverse = self._get_transform()
                    lo, hi = forward(between)
                    ticks = inverse(np.linspace(lo, hi, num=count))
                else:
                    ticks = np.linspace(*between, num=count)
                major_locator = FixedLocator(ticks)

        elif every is not None:
            if between is None:
                major_locator = MultipleLocator(every)
            else:
                lo, hi = between
                ticks = np.arange(lo, hi + every, every)
                major_locator = FixedLocator(ticks)

        elif at is not None:
            major_locator = FixedLocator(at)

        else:
            if log_base:
                major_locator = LogLocator(log_base)
            elif symlog_thresh:
                major_locator = SymmetricalLogLocator(linthresh=symlog_thresh, base=10)
            else:
                major_locator = AutoLocator()

        if minor is None:
            minor_locator = LogLocator(log_base, subs=None) if log_base else None
        else:
            if log_base:
                subs = np.linspace(0, log_base, minor + 2)[1:-1]
                minor_locator = LogLocator(log_base, subs=subs)
            else:
                minor_locator = AutoMinorLocator(minor + 1)

        return major_locator, minor_locator
def creation_plot_P(plot_parameters):
    nlines = 3
    size_figure = (6,2.3*nlines) #height of the figure depends on the number of pair we display    
    plt.close(1)

    fig = plt.figure(figsize = (size_figure[0],size_figure[1]))
    
    gs = GridSpec(nlines,2,width_ratios=[1,2],top = 0.88, bottom = 0.12, 
                  right = 0.95, left = 0.15, wspace = 0, hspace = 0.03)
    ax1 = fig.add_subplot(gs[0,1])
    ax2 = fig.add_subplot(gs[1,1])    
    ax3 = fig.add_subplot(gs[2,1])
    
    ax11 = fig.add_subplot(gs[0,0],sharey=ax1)
    ax22 = fig.add_subplot(gs[1,0],sharey=ax2)
    ax33 = fig.add_subplot(gs[2,0],sharey=ax3)
     
    major_xticks = np.arange(-5,1.5,1)
    minor_xticks = np.arange(-5,1.5,0.2)
    #apply setup    
    for ax in [ax11,ax22,ax33]:
        ax.set_xticks(major_xticks)
        ax.set_xticks(minor_xticks, minor=True)
        ax.set_xlim(-1,1)
        ax.set_facecolor((1,1,1,0))

    for ax in [ax1,ax2,ax3]:
        ax.set_xlim(1,275)
        ax.set_xscale('log')
        plt.setp(ax.get_xticklabels()[1], visible=False) 
        ax.tick_params(labelleft=False)
        
    for ax in [ax11,ax1,ax22,ax2]:
        ax.tick_params(labelbottom=False)

    for ax in [ax1,ax2,ax3,ax11,ax22,ax33]:
        ax.xaxis.set_ticks_position('both')
        ax.tick_params(which = 'both', labelsize = plot_parameters["size_font_ticks"],
                       width = plot_parameters["size_lines"]/2)
        majorLocator = AutoLocator()
        minorLocator = AutoMinorLocator()                                                        
        ax.yaxis.set_ticks_position('both')
        ax.yaxis.set_major_locator(majorLocator)
        ax.yaxis.set_minor_locator(minorLocator)
        plt.autoscale(axis='y')
        ax.tick_params(which = 'both', labelsize = plot_parameters["size_font_ticks"], 
                       width = plot_parameters["size_lines"]/2)   
                        
    ax0 = fig.add_subplot(111, frameon=False)
    plt.tick_params(labeltop=False, top=False, labelbottom=False, bottom=False, 
                    labelleft=False, left=False, labelright = False, right=False)
    ax0.set_xlabel(r'Pressure (GPa)', fontweight = 'bold', fontsize = plot_parameters["size_fonts"], 
                   labelpad = plot_parameters["shift_labelpad"])
    return fig, ax1, ax2, ax3, ax11, ax22, ax33, ax0
Пример #7
0
def creation_plot(plot_parameters, atom_couple):
    """     ********** Creation of the plot  **********    """
    print("I use creation plot without insert")
    #parameters for article format
    size_fonts = plot_parameters["size_fonts"]
    size_font_ticks = plot_parameters["size_font_ticks"]
    size_figure = plot_parameters["size_figure"]
    size_markers = plot_parameters["size_markers"]
    size_lines = plot_parameters["size_lines"]
    shift_labelpad = plot_parameters["shift_labelpad"]

    #plot
    plt.close()
    fig, (ax1, ax2) = plt.subplots(1,
                                   2,
                                   sharex=True,
                                   sharey=False,
                                   figsize=size_figure)
    #Adjustment of ticks
    major_xticks = np.arange(0, 9, 1)
    minor_xticks = np.arange(0, 8.5, 0.5)
    for ax in [ax1, ax2]:
        majorLocator = AutoLocator()
        minorLocator = AutoMinorLocator()
        ax.yaxis.set_major_locator(majorLocator)
        ax.yaxis.set_minor_locator(minorLocator)
        ax.yaxis.set_major_formatter(
            FormatStrFormatter('%.1f'))  #set one decimal to ticks label``
        plt.autoscale(enable=True, axis='y', tight=False)
        ax.yaxis.set_ticks_position('both')
        ax.set_ylabel(r'g$_{\mathrm{\bf' + atom_couple + '}}$(r)',
                      fontsize=size_fonts,
                      fontweight='bold',
                      labelpad=shift_labelpad)

        ax.set_xticks(major_xticks)
        ax.set_xticks(minor_xticks, minor=True)
        ax.set_xlim([0, 8])
        ax.set_xlabel('Distance r ($\AA$)',
                      fontsize=size_fonts,
                      fontweight='bold',
                      labelpad=shift_labelpad)

        ax.tick_params(which='both',
                       labelsize=size_font_ticks,
                       width=size_lines / 2)
    #Fine-tune figure
    plt.subplots_adjust(top=0.97,
                        bottom=0.12,
                        right=0.89,
                        left=0.07,
                        hspace=0,
                        wspace=0.27)
    return fig, ax1, ax2
Пример #8
0
def _set_zaxis_ticks(ax, lightcone, zticks, z_axis):
    if zticks != "distance":
        loc = AutoLocator()
        # Get redshift ticks.
        lc_z = lightcone.lightcone_redshifts

        if zticks == "redshift":
            coords = lc_z
        elif zticks == "frequency":
            coords = 1420 / (1 + lc_z) * un.MHz
        else:
            try:
                coords = getattr(lightcone.cosmo_params.cosmo, zticks)(lc_z)
            except AttributeError:
                raise AttributeError(
                    "zticks '{}' is not a cosmology function.".format(zticks)
                )

        zlabel = " ".join(z.capitalize() for z in zticks.split("_"))
        units = getattr(coords, "unit", None)
        if units:
            zlabel += " [{}]".format(str(coords.unit))
            coords = coords.value

        ticks = loc.tick_values(coords.min(), coords.max())

        if ticks.min() < coords.min() / 1.00001:
            ticks = ticks[1:]
        if ticks.max() > coords.max() * 1.00001:
            ticks = ticks[:-1]

        if coords[1] < coords[0]:
            ticks = ticks[::-1]

        if zticks == "redshift":
            z_ticks = ticks
        elif zticks == "frequency":
            z_ticks = 1420 / ticks - 1
        else:
            z_ticks = [
                z_at_value(getattr(lightcone.cosmo_params.cosmo, zticks), z * units)
                for z in ticks
            ]

        d_ticks = (
            lightcone.cosmo_params.cosmo.comoving_distance(z_ticks).value
            - lightcone.lightcone_distances[0]
        )
        getattr(ax, "set_{}ticks".format(z_axis))(d_ticks)
        getattr(ax, "set_{}ticklabels".format(z_axis))(ticks)

    else:
        zlabel = "Line-of-Sight Distance [Mpc]"
    return zlabel
Пример #9
0
 def set_default_locators_and_formatters(self, axis):
     # docstring inherited
     axis.set_major_locator(AutoLocator())
     axis.set_major_formatter(ScalarFormatter())
     axis.set_minor_formatter(NullFormatter())
     # update the minor locator for x and y axis based on rcParams
     if (axis.axis_name == 'x' and mpl.rcParams['xtick.minor.visible'] or
             axis.axis_name == 'y' and mpl.rcParams['ytick.minor.visible']):
         axis.set_minor_locator(AutoMinorLocator())
     else:
         axis.set_minor_locator(NullLocator())
Пример #10
0
def gridded_axis(ax):
    """
    Plot major, minor ticks as well as a grid
    :param ax:
    :return:
    """
    # Set number of major and minor ticks
    ax.xaxis.set_major_locator(AutoLocator())
    ax.xaxis.set_minor_locator(AutoLocator())
    ax.yaxis.set_major_locator(AutoLocator())
    ax.yaxis.set_minor_locator(AutoLocator())

    # Create nice-looking grid for ease of visualization
    ax.grid(which='minor', alpha=0.2, linestyle='--')
    ax.grid(which='major', alpha=0.5, linestyle='--')

    # For y-axis, format the numbers
    scale = 1
    ticks = tkr.FuncFormatter(lambda x, pos: '{:0,d}'.format(int(x / scale)))
    ax.yaxis.set_major_formatter(ticks)
Пример #11
0
 def set_default_locators_and_formatters(self, axis):
     """
     Override to set up the locators and formatters to use with the
     scale.  This is only required if the scale requires custom
     locators and formatters.  Writing custom locators and
     formatters is rather outside the scope of this example, but
     there are many helpful examples in ``ticker.py``.
     """
     axis.set_major_locator(AutoLocator())
     axis.set_major_formatter(ScalarFormatter())
     axis.set_minor_formatter(ScalarFormatter())
     return
def creation_plot(plot_parameters):
    nlines = 3
    size_figure = (
        6, 2.3 * nlines
    )  #height of the figure depends on the number of pair we display
    plt.close(1)
    fig, (ax1, ax2, ax3) = plt.subplots(nrows=nlines,
                                        ncols=1,
                                        sharex=True,
                                        sharey=False,
                                        figsize=size_figure)
    major_xticks = np.arange(0, 8, 0.5)
    minor_xticks = np.arange(0, 8, 0.1)
    for ax in [ax1, ax2, ax3]:
        ax.set_xticks(major_xticks)
        ax.set_xticks(minor_xticks, minor=True)
        ax.set_xlim(0.9, 5.58)
        ax.xaxis.set_ticks_position('both')
        majorLocator = AutoLocator()
        minorLocator = AutoMinorLocator()
        ax.yaxis.set_ticks_position('both')
        ax.yaxis.set_major_locator(majorLocator)
        ax.yaxis.set_minor_locator(minorLocator)

        plt.autoscale(axis='y')
        ax.tick_params(which='both',
                       labelsize=plot_parameters["size_font_ticks"],
                       width=plot_parameters["size_lines"] / 2)
    # Fine-tune figure : 1) make subplots close to each other (+ less whitespace around), 2) hide x ticks for all but bottom plot, 3) add a big invisible subplot in order to center x and y labels (since the ticklabels are turned off we have to move the x and y labels with labelpad)
    fig.subplots_adjust(top=0.95,
                        bottom=0.1,
                        right=0.95,
                        left=0.1,
                        hspace=0.03,
                        wspace=0.02)
    ax0 = fig.add_subplot(111, frameon=False)
    plt.tick_params(labeltop=False,
                    top=False,
                    labelbottom=False,
                    bottom=False,
                    labelleft=False,
                    left=False,
                    labelright=False,
                    right=False)
    ax0.set_xlabel(r'Density (g.cm$^{-3}$)',
                   fontweight='bold',
                   fontsize=plot_parameters["size_fonts"],
                   labelpad=plot_parameters["shift_labelpad"])
    ax0.set_ylabel(r'Coordination number',
                   fontweight='bold',
                   fontsize=plot_parameters["size_fonts"],
                   labelpad=plot_parameters["shift_labelpad"])
    return fig, ax1, ax2, ax3, ax0
Пример #13
0
def plotmerge(n=3):
    """plot merging traps with n timesteps"""
    sep = np.linspace(0, max([Cswaist,Rbwaist])*2, n)     # initial separation of the tweezer traps
    xs = np.linspace(-max(sep)*0.5, max(sep)*1.5, 200)    # positions along the beam axis

    for atoms in [[Rb1064, Rb880, wrRb], [Cs1064, Cs880, wrCs]]:
        plt.figure(figsize=(6,7.5))
        
        for i in range(n):
            ax = plt.subplot2grid((n,1), (i,0))
            if atoms[0].X == 'Rb':
                minU0 = (atoms[0].acStarkShift(0,0,0,mj=0) + atoms[1].acStarkShift(0,0,0,mj=0))/kB*1.1e3
                maxU0 = 0.16
            elif atoms[0].X=='Cs':
                minU0 = atoms[0].acStarkShift(0,0,0,mj=0)/kB*1.1e3
                maxU0 = atoms[1].acStarkShift(0,0,0,mj=0)/kB*1.1e3
            # combined potential along the beam axis:
            U = (atoms[0].acStarkShift(xs,0,0,mj=0) + atoms[1].acStarkShift(xs-sep[n-i-1],0,0,mj=0))/kB*1e3 
            U1064 = atoms[0].acStarkShift(xs,0,0,mj=0)/kB*1e3         # potential in the 1064 trap
            U880 = atoms[1].acStarkShift(xs-sep[n-i-1],0,0,mj=0)/kB*1e3 # potential in the 880 trap
            plt.plot(xs*1e6, U, 'k')
            plt.plot(xs*1e6, U1064, color=default_colours.DUcherry_red, alpha=0.6)
            plt.plot(xs*1e6, U880, color=default_colours.DUsea_blue, alpha=0.6)
            plt.plot([0]*2, [minU0,maxU0], color=default_colours.DUcherry_red, linewidth=10, label='%.0f'%(Cswl*1e9), alpha=0.4)
            plt.plot([sep[n-i-1]*1e6]*2, [minU0,maxU0], color=default_colours.DUsea_blue, linewidth=10, label='%.0f'%(Rbwl*1e9), alpha=0.4)
            ax.set_xticks([])
            ax.set_ylim((minU0,maxU0))
            ax.set_xlim((xs[0]*1e6, xs[-1]*1e6))
            # ax.set_yticks([])
            

            if i == 0:
                if atoms[0].X == 'Rb':
                    ax.set_title('a)', pad=30)
                elif atoms[0].X == 'Cs':
                    ax.set_title('b)', pad=30)
        #         ax.set_title("Optical potential experienced by "+atoms[0].X
        # +"\n%.0f beam power: %.3g mW   %.0f beam power: %.3g mW"%(Cswl*1e9, power*1e3, Rbwl*1e9, Rbpower*1e3),
        #             pad = 30)
                plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.)
                # ax.text(xs[0]*1e6, 0, '$\omega/2\pi = %.0f$ kHz'%(trap_freq(atoms[0])/afu), 
                #                                         bbox=dict(facecolor='white', edgecolor=None))
                # ax.text(sep[-1]*1e6,0,'$\omega/2\pi = %.0f$ kHz'%(trap_freq(atoms[1])/afu), 
                #                                         bbox=dict(facecolor='white', edgecolor=None))
        
            
        plt.xlabel(r'Position ($\mu$m)')
        ax.set_xticks(sep*1e6)
        plt.ylabel('Trap Depth (mK)')
        # ax.text(xs[0]*1e6, 0, '$\omega/2\pi = %.0f$ kHz'%atoms[2], bbox=dict(facecolor='white', edgecolor=None))
        ax.yaxis.set_major_locator(AutoLocator())
        plt.tight_layout()
        plt.subplots_adjust(hspace=0.02)
Пример #14
0
def print_mat():
    fig1 = plt.figure()
    ax1 = fig1.add_subplot(1, 1, 1)
    ax1.xaxis.set_major_formatter(DateFormatter('%m-%d'))  #设置时间标签显示格式
    ax1.xaxis.set_major_locator(AutoDateLocator())  #设置x轴自动时间刻度
    ax1.yaxis.set_major_locator(AutoLocator())  #设置y轴自动刻度
    plt.plot(Date, Open, label="Open", color="red")
    plt.plot(Date, Close, label="Close", color="blue")
    plt.title(u"抓取特斯拉股票历史开盘、收盘价格", fontproperties=font)
    plt.xlabel("时间", fontproperties=font)
    plt.legend()
    plt.show()
Пример #15
0
 def setup_plot_for_right_frame(self, parent_frame):
     figure = Figure(dpi=100)
     self.plot = figure.add_subplot(111)
     self.plot.grid(**PropertiesDictionaries.grid_properties_dict)
     self.plot.xaxis.set_major_locator(AutoLocator())
     self.plot.xaxis.set_minor_locator(AutoMinorLocator(4))
     self.plot.yaxis.set_major_locator(AutoLocator())
     self.plot.yaxis.set_minor_locator(AutoMinorLocator(4))
     self.plot.tick_params(
         **dict(
             list(
                 PropertiesDictionaries.ticks_properties_dict.items())[:2]),
         **dict(
             list(PropertiesDictionaries.ticks_properties_dict.items())
             [3:7]),
         **dict(
             list(
                 PropertiesDictionaries.ticks_properties_dict.items())[8:]))
     mat_art.setp(self.plot, **PropertiesDictionaries.axes_properties_dict)
     self.plot.autoscale()
     ChartCreator.chosen_plot_label = ttk.Label(
         parent_frame,
         text="Chosen: ",
         width=24,
         justify="left",
         font=Constants.MONOSPACED_FONT)
     ChartCreator.chosen_plot_label.grid(row=1, column=1, sticky="ew")
     self.canvas = FigureCanvasTkAgg(figure, parent_frame)
     self.canvas.mpl_connect("pick_event",
                             self.event_handler.click_artist_callback)
     self.canvas.show()
     self.canvas.get_tk_widget().grid(row=0,
                                      column=0,
                                      columnspan=2,
                                      sticky="nwse")
     toolbar_frame = tk.Frame(parent_frame)
     toolbar_frame.grid(row=1, column=0, sticky="w")
     toolbar = NavigationToolbar2TkAgg(self.canvas, toolbar_frame)
     toolbar.update()
     self.canvas._tkcanvas.grid()
Пример #16
0
def update_ticks(axes, coord, components, is_log):
    """
    Changes the axes to have the proper tick formatting based on the type of
    component.

    Returns `None` or the number of categories if components is Categorical.

    Parameters
    ----------
    axes : `~matplotlib.axes.Axes`
        A matplotlib axis object to alter
    coord : { 'x' | 'y' }
        The coordinate axis on which to update the ticks
    components : iterable
        A list of components that are plotted along this axis
    if_log : boolean
        Whether the axis has a log-scale
    """

    if coord == 'x':
        axis = axes.xaxis
    elif coord == 'y':
        axis = axes.yaxis
    else:
        raise TypeError("coord must be one of x,y")

    is_cat = any(comp.categorical for comp in components)
    is_date = any(comp.datetime for comp in components)

    if is_date:
        loc = AutoDateLocator()
        fmt = AutoDateFormatter(loc)
        axis.set_major_locator(loc)
        axis.set_major_formatter(fmt)
    elif is_log:
        axis.set_major_locator(LogLocator())
        axis.set_major_formatter(LogFormatterMathtext())
    elif is_cat:
        all_categories = np.empty((0, ), dtype=np.object)
        for comp in components:
            all_categories = np.union1d(comp.categories, all_categories)
        locator = MaxNLocator(10, integer=True)
        locator.view_limits(0, all_categories.shape[0])
        format_func = partial(tick_linker, all_categories)
        formatter = FuncFormatter(format_func)

        axis.set_major_locator(locator)
        axis.set_major_formatter(formatter)
        return all_categories.shape[0]
    else:
        axis.set_major_locator(AutoLocator())
        axis.set_major_formatter(ScalarFormatter())
Пример #17
0
 def set_default_locators_and_formatters(self, axis):
     """
     Set the locators and formatters to reasonable defaults for
     linear scaling.
     """
     axis.set_major_locator(AutoLocator())
     axis.set_major_formatter(ScalarFormatter())
     axis.set_minor_formatter(NullFormatter())
     # update the minor locator for x and y axis based on rcParams
     if rcParams['xtick.minor.visible']:
         axis.set_minor_locator(AutoMinorLocator())
     else:
         axis.set_minor_locator(NullLocator())
 def set_default_locators_and_formatters(self, axis):
     """
     Set the locators and formatters to the same defaults as the
     linear scale.
     """
     axis.set_major_locator(AutoLocator())
     axis.set_major_formatter(ScalarFormatter())
     axis.set_minor_formatter(NullFormatter())
     # update the minor locator for x and y axis based on rcParams
     if (axis.axis_name == 'x' and rcParams['xtick.minor.visible']
         or axis.axis_name == 'y' and rcParams['ytick.minor.visible']):
         axis.set_minor_locator(AutoMinorLocator())
     else:
         axis.set_minor_locator(NullLocator())
Пример #19
0
    def apply_commands(self):
        from matplotlib.ticker import LogLocator, AutoLocator

        for key in sorted(self.ydata.keys()):
            ig, ip = key

            xdata = nm.array(self.xdata[(ig, ip)])
            ydata = nm.array(self.ydata[(ig, ip)])

            ax = self.ax[ig]
            if self.clear_axes[ig]:
                ax.cla()
                self.clear_axes[ig] = False

            ax.set_yscale(self.yscales[ig])
            ax.yaxis.grid(True)
            draw_data(ax, nm.array(xdata), nm.array(ydata),
                      self.data_names[ig][ip], self.plot_kwargs[ig][ip])

            if self.yscales[ig] == 'log':
                ymajor_formatter = ax.yaxis.get_major_formatter()
                ymajor_formatter.label_minor(True)
                yminor_locator = LogLocator()
            else:
                yminor_locator = AutoLocator()
                self.ax[ig].yaxis.set_minor_locator(yminor_locator)

        if self.show_legends:
            for ig, ax in enumerate(self.ax):
                try:
                    ax.legend()
                except:
                    pass

                if self.xlabels[ig]:
                    ax.set_xlabel(self.xlabels[ig])
                if self.ylabels[ig]:
                    ax.set_ylabel(self.ylabels[ig])

                for x, kwargs in self.vlines[ig]:
                    ax.axvline(x, **kwargs)

            try:
                self.plt.tight_layout(pad=0.5)

            except:
                pass
Пример #20
0
    def update_plot(self):
        if len(self.Plotsignals) == 0:
            return
        self.ax.clear()
        for Plotsignal in self.Plotsignals:
            if Plotsignal.plotenable:
                if Plotsignal.plotnormalise:
                    data = Plotsignal.get_normalised_values() * 100
                    self.ax.plot(data, color=Plotsignal.plotcolor)
                else:
                    data = Plotsignal.get_values()
                    self.ax.plot(convert_to_si(Plotsignal.unit, data)[1],
                                 color=Plotsignal.plotcolor)

        self.ax.grid(True)
        self.ax.get_yaxis().tick_right()
        self.ax.get_yaxis().set_label_position("right")
        self.ax.get_yaxis().set_visible(True)
        self.ax.get_xaxis().set_visible(False)
        all_normalised = True
        all_same_unit = True
        unit = ""
        iter = self.signalstore.get_iter(0)
        while iter is not None:
            if self.signalstore[iter][0] == True:
                if unit == "":
                    unit = self.signalstore[iter][4]
                if self.signalstore[iter][1] == False:
                    all_normalised = False
                if self.signalstore[iter][4] != unit:
                    all_same_unit = False
            if not all_normalised and not all_same_unit:
                break
            iter = self.signalstore.iter_next(iter)
        if all_normalised:
            self.ax.set_yticks(np.arange(0, 101, step=25))
            self.ax.set_ylabel('Percent [%]')
        else:
            self.ax.yaxis.set_major_locator(AutoLocator())
            if all_same_unit:
                self.ax.set_ylabel(unit)
            else:
                self.ax.set_ylabel("")
        self.canvas.draw()
        self.canvas.flush_events()
def creation_plot(xlabel):
    """     ********** Creation of the plot  **********    """
    plt.close()
    fig, ax = plt.subplots(figsize=(10, 4))
    ax.set_ylabel(r'Cluster absolute lifetime (fs)',
                  fontweight='bold',
                  fontsize=12)
    ax.set_xlabel(xlabel, fontweight='bold', fontsize=12, labelpad=25)
    #Adjustment of ticks
    ymajorLocator = AutoLocator()
    yminorLocator = AutoMinorLocator()
    ax.yaxis.set_major_locator(ymajorLocator)
    ax.yaxis.set_minor_locator(yminorLocator)
    ax.tick_params(which='both', labelsize=10, width=0.5)
    plt.tick_params(bottom=False, top=False, labelbottom=True)
    plt.autoscale(enable=True, axis='y', tight=True)
    ax.grid(True, which='major', axis='y', linestyle=':', linewidth=0.5)
    return fig, ax
Пример #22
0
def plotLevels(data):
    assert span1 == span2
    span = span1
    # ---------------------- create the figure and axes ---------------------- #
    fig, ax = plt.subplots()

    # -- discretize the definition space and compute the function's images --- #
    X, Y = discretise_space([defspace1, defspace2], n=span)
    Z = data

    cs = ax.contourf(X, Y, Z, locator=AutoLocator(), cmap=cm.PuBu)

    # ---------------------------- titles & misc ----------------------------- #
    cbar = fig.colorbar(cs)  # bar with scales

    ax.set(xlabel='$W\_C$', ylabel='$W\_W$')  #,
    #title='Utilité à {} ticks en fonction de W_W et W_C'.format(ticks))
    plt.show()
Пример #23
0
def plotStudRes(ax, d, xx , yerr, res_tick, x0=0, left=0):
    stu_d = d/yerr
    stu_d_err = np.ones(len(d))
    divider = make_axes_locatable(ax)
    ax2 = divider.append_axes("top", size="20%", pad=0.1)
    ax.figure.add_axes(ax2)
    ax2.set_xlim(ax.get_xlim())
    ax2.set_yticks(res_tick)
    ax.tick_params(width=1.3, axis='both', direction='in', bottom=True, top=True, left=True, right=True)
    ax2.tick_params(width=1.3, axis='both', direction='in', bottom=True, top=True, left=True, right=True, labelbottom=False)
    ax2.set_ylabel('Studentized\nResiduals', color='k', fontsize=12)
    from matplotlib.ticker import AutoLocator, AutoMinorLocator
    ax2.get_yaxis().set_major_locator(AutoLocator())
#    ax2.get_yaxis().set_minor_locator(AutoMinorLocator())
    ax2.axhline(y=0, color='r', linestyle='-', linewidth=2)
    ax.tick_params(axis='both', direction='in')
    ax2.tick_params(axis='both', direction='in')
    ax2.errorbar(xx+x0-left, stu_d, yerr=stu_d_err, fmt='o', elinewidth=1.5 ,capsize=2, ecolor='b', \
                 label='Data', linestyle='None', markersize=3 ,color='k')
Пример #24
0
 def set_xticks(self, ticks=None):
     if ticks:
         super(Radialplot, self).set_xticks(ticks)
     else:
         if self.transform == "linear":
             loc = AutoLocator()
             ticks = loc.tick_values(0., self.max_x)
             ticks2 = loc.tick_values(min(self.sez), max(self.sez))
             ticks2 = ticks2[::-1]
             ticks2[-1] = min(self.sez)
             super(Radialplot, self).set_xticks(1.0 / ticks2)
             labels = ["{0:5.1}".format(val) for val in ticks2]
             self.xaxis.set_ticklabels(labels)
             self.spines["bottom"].set_bounds(0., 1. / ticks2[-1])
             self.set_xlabel(r'$\sigma$')
         else:
             loc = MaxNLocator(5)
             ticks = loc.tick_values(0., self.max_x)
             super(Radialplot, self).set_xticks(ticks)
             self.spines["bottom"].set_bounds(ticks[0], ticks[-1])
Пример #25
0
def update_ticks(axes, coord, components, is_log):
    """
    Changes the axes to have the proper tick formatting based on the type of
    component.

    :param axes: A matplotlib axis object to alter
    :param coord: 'x' or 'y'
    :param components: A list() of components that are plotted along this axis
    :param is_log: Boolean for log-scale.
    :kwarg max_categories: The maximum number of categories to display.
    :return: None or #categories if components is Categorical
    """

    if coord == 'x':
        axis = axes.xaxis
    elif coord == 'y':
        axis = axes.yaxis
    else:
        raise TypeError("coord must be one of x,y")

    is_cat = all(comp.categorical for comp in components)
    if is_log:
        axis.set_major_locator(LogLocator())
        axis.set_major_formatter(LogFormatterMathtext())
    elif is_cat:
        all_categories = np.empty((0, ), dtype=np.object)
        for comp in components:
            all_categories = np.union1d(comp.categories, all_categories)
        locator = MaxNLocator(10, integer=True)
        locator.view_limits(0, all_categories.shape[0])
        format_func = partial(tick_linker, all_categories)
        formatter = FuncFormatter(format_func)

        axis.set_major_locator(locator)
        axis.set_major_formatter(formatter)
        return all_categories.shape[0]
    else:
        axis.set_major_locator(AutoLocator())
        axis.set_major_formatter(ScalarFormatter())
Пример #26
0
def creation_plot(speciation):
    """     ********** Creation of the plot  **********    """
    plt.close()
    fig, ax = plt.subplots(figsize=(8,5))
    if speciation == '1':
        xlabel = 'Chemical species'
    else:
        xlabel = 'Coordinating polyhedra'
    ax.set_ylabel(r'Cluster absolute lifetime (fs)', fontweight = 'bold', fontsize = 12)
    ax.set_xlabel(xlabel, fontweight = 'bold', fontsize = 12)
    ax.xaxis.set_label_coords(0.5, -0.3)
    ax.yaxis.set_label_coords(-0.1, 0.5)
    #Adjustment of ticks
    ymajorLocator = AutoLocator()
    yminorLocator = AutoMinorLocator()
    ax.yaxis.set_major_locator(ymajorLocator)
    ax.yaxis.set_minor_locator(yminorLocator)
    ax.tick_params(which = 'both', labelsize = 10, width = 0.5)
    #plt.autoscale(enable=True,axis='y',tight=True)
    #ax.set_ylim(0,770) #for NaAlSi3O8 a19.0
    #ax.set_ylim(0,60) #for NaAlSi3O8 a15.0
    plt.tick_params(bottom = False, top = False, labelbottom = True)
    ax.grid(True, which='major',axis = 'y', linestyle=':', linewidth=0.5  )
    return fig,ax
Пример #27
0
def draw_pic(dataframe, currency):
    # check types
    if not isinstance(dataframe, pd.DataFrame):
        raise TypeError(
            '{} should be Pandas.DataFrame object'.format(dataframe))
    if not (currency == 'dol') | (currency == 'eur'):
        raise NameError('{} should be \'dol\' or \'eur\''.format(currency))

    # Draw pic
    fig, ax = plt.subplots(figsize=(10, 7))

    mean_val = dataframe.loc[:, ['High', 'Low']].mean(axis=1)
    x_values = dataframe.index.strftime('%b %d')

    ax.fill_between(x_values,
                    dataframe['High'],
                    dataframe['Low'],
                    color='Purple',
                    alpha=0.2)
    ax.plot(x_values, mean_val, linewidth=2, color='Purple')

    ax.tick_params(axis='x', direction='out', length=8)
    ax.xaxis.set_major_locator(MultipleLocator(4))
    ax.yaxis.set_major_locator(AutoLocator())
    ax.xaxis.set_minor_locator(AutoMinorLocator())
    ax.grid(which='both')
    for tick in ax.get_xticklabels():
        tick.set_rotation(45)
    if currency == 'dol':
        ax.set_title('USD/RUB', fontsize=16, pad=25)
        ax.set_ylabel('RUB per USD')
        fig.savefig('picDol.png')
    if currency == 'eur':
        ax.set_title('EUR/RUB', fontsize=16, pad=25)
        ax.set_ylabel('RUB per EUR')
        fig.savefig('picEur.png')
Пример #28
0
def plot(ts,
         figure_width=12,
         linewidth=1,
         marker=".",
         color="mediumvioletred",
         aspect_ratio=None,
         font=None):
    if font is None:
        available_fonts = set(f.name for f in font_manager.fontManager.ttflist)
        for font in FONTS:
            if font in available_fonts:
                break

    if aspect_ratio is None:
        try:
            n_unique_values = len(ts.distribution())
        except KeyError:
            n_unique_values = 0
        scaled = min(MAX_ASPECT_POINTS, max(2, n_unique_values) - 2)
        aspect_ratio = MIN_ASPECT_RATIO + (
            MAX_ASPECT_RATIO - MIN_ASPECT_RATIO) * (scaled / MAX_ASPECT_POINTS)

    with plt.style.context('seaborn'):
        fig, ax = plt.subplots(figsize=(figure_width,
                                        aspect_ratio * figure_width))
        items = ts.items()
        x, y = zip(*items) if items else ([], [])
        ax.scatter(x, y, linewidth=linewidth, marker=marker, color=color)
        ax.set_aspect(75)
        ax.xaxis.set_minor_locator(AutoMinorLocator())
        ax.xaxis.set_major_locator(AutoLocator())
        if font:
            plt.xticks(fontname=font)
            plt.yticks(fontname=font)

    return fig, ax
Пример #29
0
    def process_command(self, command):
        from matplotlib.ticker import LogLocator, AutoLocator

        self.output(command[0])

        if command[0] == 'ig':
            self.ig = command[1]

        elif command[0] == 'plot':
            xdata, ydata, plot_kwargs = command[1:]

            ig = self.ig
            ax = self.ax[ig]
            ax.set_yscale(self.yscales[ig])
            ax.yaxis.grid(True)
            ax.plot(xdata, ydata, **plot_kwargs)

            if self.yscales[ig] == 'log':
                ymajor_formatter = ax.yaxis.get_major_formatter()
                ymajor_formatter.label_minor(True)
                yminor_locator = LogLocator()
            else:
                yminor_locator = AutoLocator()
                self.ax[ig].yaxis.set_minor_locator(yminor_locator)

        elif command[0] == 'vline':
            x, kwargs = command[1:]

            self.vlines[self.ig].append((x, kwargs))

        elif command[0] == 'clear':
            self.ax[self.ig].cla()

        elif command[0] == 'legends':
            for ig, ax in enumerate(self.ax):
                try:
                    ax.legend(self.data_names[ig])
                except:
                    pass

                if self.xlabels[ig]:
                    ax.set_xlabel(self.xlabels[ig])
                if self.ylabels[ig]:
                    ax.set_ylabel(self.ylabels[ig])

                for x, kwargs in self.vlines[ig]:
                    ax.axvline(x, **kwargs)

            try:
                self.plt.tight_layout(pad=0.5)

            except:
                pass

        elif command[0] == 'add_axis':
            ig, names, yscale, xlabel, ylabel = command[1:]
            self.data_names[ig] = names
            self.yscales[ig] = yscale
            self.xlabels[ig] = xlabel
            self.ylabels[ig] = ylabel
            self.n_gr = len(self.data_names)
            self.make_axes()

        elif command[0] == 'save':
            self.fig.savefig(command[1])
            self.pipe.send(True)  # Acknowledge save.
Пример #30
0
from __future__ import division
from builtins import range
from past.utils import old_div
import numpy as np
import matplotlib.pyplot as plt
from boututils.file_import import file_import
from matplotlib.ticker import FixedFormatter, FormatStrFormatter, AutoLocator, AutoMinorLocator

g = file_import("data/cbm18_dens8.grid_nx68ny64.nc")

majorLocator = AutoLocator()
majorFormatter = FormatStrFormatter('%3.0e')
minorLocator = AutoMinorLocator()
Fm = FixedFormatter([
    '0', '$1 \\times 10^4$', '$2 \\times  10^4$', '$3 \\times 10^4$',
    '$4 \\times 10^4$'
])
Fm2 = FixedFormatter(
    ['0', '$2 \\times 10^5$', '$4 \\times  10^5$', '$6 \\times 10^5$'])

bxy = g.get('Bxy')
p = g.get('pressure')
jpar0 = g.get('Jpar0')
psixy = g.get('psixy')
btxy = g.get('Btxy')
shiftangle = g.get('ShiftAngle')

nx = g.get('nx')
ny = g.get('ny')

q = np.zeros((nx, ny))