示例#1
0
 def get_new_ax(self):
     ax = AA.Subplot(self.F, self.rows, self.cols, self.current_ax_id)
     return ax
示例#2
0
import numpy as np
import matplotlib.pyplot as plt

import mpl_toolkits.axisartist as axisxy


x = np.linspace(-8,8,1000)
y = np.square(x)-2
# x=5时候的切线
x2 = np.linspace(2,6,1000)
y2 = 10*x2-27

fig = plt.figure(figsize=(4,4))
ax = axisxy.Subplot(fig,111)
fig.add_axes(ax)
ax.axis[:].set_visible(False)
ax.axis["x"] = ax.new_floating_axis(0,0)
ax.axis["x"].set_axisline_style("->",size = 1.0)

ax.axis["y"] = ax.new_floating_axis(1,0)
ax.axis["y"].set_axisline_style("-|>", size = 1.0)

ax.axis["x"].set_axis_direction("top")
ax.axis["y"].set_axis_direction("right")

plt.plot(x,y,'b')
plt.plot(x2,y2,'r')  
plt.show()
示例#3
0
    def plot(self, *args):
        """
        Plot all tracks.

        >>> from coolbox.api import *
        >>> frame = XAxis() + XAxis()
        >>> frame.plot("chr1", 100000, 200000)
        >>> frame.plot("chr1:100000-200000")
        """
        if len(args) == 3:
            gr = GenomeRange(*args[:3])
            gr2 = None
        elif len(args) == 1:
            gr = GenomeRange(args[0])
            gr2 = None
        elif len(args) == 6:
            gr = GenomeRange(args[:3])
            gr2 = GenomeRange(args[3:])
        elif len(args) == 2:
            gr = GenomeRange(args[0])
            gr2 = GenomeRange(args[1])
        elif self.current_range:
            gr = self.current_range
            gr2 = None
        else:
            raise ValueError("Please specify a genomic range in uscs format. For example: 'chr1:100000-200000'")
        # cache for the previous GenomeRange
        self.goto(gr, gr2)

        tracks_height = self.get_tracks_height()
        self.properties['height'] = sum(tracks_height)

        fig = plt.figure(figsize=cm2inch(self.properties['width'],
                                         self.properties['height']))
        if 'title' in self.properties:
            fig.suptitle(self.properties['title'])

        grids = matplotlib.gridspec.GridSpec(
            len(tracks_height), 3,
            height_ratios=tracks_height,
            width_ratios=self.properties['width_ratios'],
            wspace=0.01)

        axis_list = []
        for idx, track in enumerate(self.tracks.values()):
            y_ax = plt.subplot(grids[idx, 0])
            y_ax.set_axis_off()

            ax = axisartist.Subplot(fig, grids[idx, 1])
            fig.add_subplot(ax)
            ax.axis[:].set_visible(False)
            ax.patch.set_visible(False)

            label_ax = plt.subplot(grids[idx, 2])
            label_ax.set_axis_off()

            track.label_ax = label_ax
            track.y_ax = y_ax
            try:
                # Attention, copy is necessary, otherwise GenomeRange may change due to call of gr.change_chrom_names
                track.plot(ax, copy(gr), gr2=copy(gr2))

            except Exception as e:
                import sys, os
                exc_type, exc_obj, exc_tb = sys.exc_info()
                fname = exc_tb.tb_frame.f_code.co_filename
                log.error("Error occured when plot track:\n"
                          "\ttrack name: {}\n\ttrack type:{}\n"
                          "\tError: {} {}\n"
                          "\toccurred in \"{}\", line {}".format(
                    track.name, type(track),
                    type(e), str(e), fname, exc_tb.tb_lineno)
                )
                log.exception(e)
            track.plot_coverages(ax, gr, gr2)

            axis_list.append(ax)

        margins = self.properties['margins']
        fig.subplots_adjust(wspace=0, hspace=0.0,
                            left=margins['left'],
                            right=margins['right'],
                            bottom=margins['bottom'],
                            top=margins['top'])

        plt.close()

        return fig
示例#4
0
import numpy as np  #导入数值计算模块
import matplotlib.pyplot as plt  #导入绘图模块
import mpl_toolkits.axisartist as axisartist  #导入坐标轴加工模块

fig = plt.figure()  #新建画布
ax = axisartist.Subplot(fig, 1, 1, 1)  #使用axisartist.Subplot方法创建一个绘图区对象ax
fig.add_axes(ax)  #将绘图区对象添加到画布中

ax.axis[:].set_visible(False)  #隐藏原来的实线矩形

ax.axis["x"] = ax.new_floating_axis(0, 0)  # 添加x轴
ax.axis["y"] = ax.new_floating_axis(1, 0)  # 添加y轴
ax.axis["x"].set_axis_direction('bottom')  # x轴刻度位置
ax.axis["y"].set_axis_direction('left')  # y轴刻度位置

ax.set_xticks(range(-4, 5))  #设置x坐标轴刻度
ax.set_yticks([-4, -3, -2, -1, 1, 2, 3, 4])  #设置y坐标轴刻度
ax.axis["x"].set_axisline_style("->", size=1.0)  #给x坐标轴加箭头
ax.axis["y"].set_axisline_style("->", size=1.0)  #给y坐标轴加箭头
ax.annotate(s='x', xy=(0, 0), xytext=(5.0, -0.4))  #x轴上标注字母
ax.annotate(s='y', xy=(0, 1.0), xytext=(0.2, 5.0))  #y轴上标注字母

plt.xlim(-5, 5)  #设置x坐标轴范围
plt.ylim(-5, 5)  #设置y坐标轴范围
plt.show()  #显示坐标轴
示例#5
0
                    pqd_17_predict_normal[i] + 1,
                    pqd_type[pqd_17_predict_normal[i]]),
                          fontsize=10)
            elif 12 <= i <= 16:
                plt.subplot(3, 6, i + 1)
                plt.plot(teX[pqd_17_index[i], ], 'b--', label='Original')
                plt.plot(adv_univer[pqd_17_index[i], ], 'r:', label='SAA')
                plt.legend()
                plt.title("C-{},{}\n(C-{},{})".format(
                    pqd_17_predict_attack_SAA[i] + 1,
                    pqd_type[pqd_17_predict_attack_SAA[i]],
                    pqd_17_predict_normal[i] + 1,
                    pqd_type[pqd_17_predict_normal[i]]),
                          fontsize=10)

        ax = axisartist.Subplot(fig, 3, 6, 6)
        plt.subplots_adjust(left=0.01, right=0.99, top=0.95, bottom=0.05)
        fig.add_axes(ax)
        ax.axis["bottom"].set_axisline_style("-|>", size=1.5)
        ax.axis["left"].set_axisline_style("-|>", size=1.5)
        ax.axis["top"].set_visible(False)
        ax.axis["bottom"].toggle(all=False, label=True)
        ax.axis["bottom"].label.set_text("Time (s)")
        ax.axis["right"].set_visible(False)
        ax.axis["left"].toggle(all=False, label=True)
        ax.axis["left"].label.set_text("Voltage/Current (V/A p.u.)")

        ax = axisartist.Subplot(fig, 3, 6, 12)
        plt.subplots_adjust(left=0.01, right=0.99, top=0.95, bottom=0.05)
        fig.add_axes(ax)
        ax.axis["bottom"].set_axisline_style("-|>", size=1.5)
示例#6
0
# -*- coding: utf-8 -*-
#具有初始相位的正弦信号

# 导入模块
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist
# 绘图
fig = plt.figure()  # 创建画布
ax = axisartist.Subplot(fig, 111)  # 创建绘图区对象ax
fig.add_axes(ax)  # 将绘图区对象添加到画布中
ax.axis[:].set_visible(False)  # 通过set_visible方法设置绘图区所有坐标轴隐藏
ax.axis["x"] = ax.new_floating_axis(0, 0)  # 添加新的坐标轴
ax.axis["x"].set_axisline_style("->", size=1.0)  # 给x轴加上箭头
ax.axis["y"] = ax.new_floating_axis(1, 0)  # 添加y轴
ax.axis["y"].set_axisline_style("-|>", size=1.0)  #y轴加箭头
ax.axis["x"].set_axis_direction("top")
ax.axis["y"].set_axis_direction("right")  # 设置x、y轴上刻度显示方向
t = np.arange(-10, 10, 0.01)
y = np.cos(t - 1)  # 函数
plt.title(r'$x(t)=A\cos(wt+\phi)$', fontsize=10)
plt.xticks([])
plt.yticks([])
plt.ylim(-2, 2)
# 标识
plt.text(-2.5, np.cos(-1), r'$A\cos\phi$', fontdict={'size': 14})
plt.text(0, -0.15, 'O', fontdict={'size': 14})
plt.text(0.15, 1.90, 'x(t)', fontdict={'size': 14})
plt.text(10, -0.15, 't', fontdict={'size': 14})
plt.text(1.2, 0.96, '<-------------->', fontdict={'size': 14})
示例#7
0
文件: pqd_SSA.py 项目: minkione/AT_SG
            model.predict(adv_SSA[pqd_17_index, ]),
            axis=1)  ### the new prediction after attack
        fig = plt.figure()
        for i in range(17):
            plt.subplot(3, 6, i + 1)
            plt.plot(teX[pqd_17_index[i], ], 'b--', label='Original')
            plt.plot(adv_SSA[pqd_17_index[i], ], 'r:', label='SSA')
            plt.legend()
            plt.title("C-{},{}\n(C-{},{})".format(
                pqd_17_predict_attack[i] + 1,
                pqd_type[pqd_17_predict_attack[i]],
                pqd_17_predict_normal[i] + 1,
                pqd_type[pqd_17_predict_normal[i]]),
                      fontsize=10)
            #plt.title('{}'.format(pqd_type[i]))
        plt.subplots_adjust(wspace=0.2, hspace=0.3)
        plt.subplots_adjust(left=0.01, right=0.99, top=0.95, bottom=0.05)
        ax = axisartist.Subplot(fig, 3, 6, 18)
        fig.add_axes(ax)
        ax.axis["bottom"].set_axisline_style("-|>", size=1.5)
        ax.axis["left"].set_axisline_style("-|>", size=1.5)
        ax.axis["top"].set_visible(False)
        ax.axis["bottom"].toggle(all=False, label=True)
        ax.axis["bottom"].label.set_text("Time (s)")
        ax.axis["right"].set_visible(False)
        ax.axis["left"].toggle(all=False, label=True)
        ax.axis["left"].label.set_text("Voltage/Current (V/A p.u.)")
        plt.show()

        print('Done')
示例#8
0
    def plot(self, file_name, chrom, start, end, title=None):
        track_height = self.get_tracks_height(start_region=start,
                                              end_region=end)

        if self.fig_height:
            fig_height = self.fig_height
        else:
            fig_height = sum(track_height)

        log.debug("Figure size in cm is {} x {}. Dpi is set to {}\n".format(
            self.fig_width, fig_height, self.dpi))
        fig = plt.figure(figsize=self.cm2inch(self.fig_width, fig_height))
        if title:
            fig.suptitle(title)

        grids = matplotlib.gridspec.GridSpec(len(track_height),
                                             3,
                                             height_ratios=track_height,
                                             width_ratios=self.width_ratios,
                                             wspace=0.01)
        axis_list = []
        # skipped_tracks is the count of tracks that have the
        # 'overlay previous' parameter and should be skipped
        skipped_tracks = 0
        plot_axis = None
        for idx, track in enumerate(self.track_obj_list):
            log.info("plotting {}".format(track.properties['section_name']))
            if idx == 0 and track.properties['overlay previous'] != 'no':
                log.warn(
                    "First track can not have the `overlay previous` option")
                track.properties['overlay previous'] = 'no'

            if track.properties['overlay previous'] in ['yes', 'share-y']:
                overlay = True
                skipped_tracks += 1
            else:
                overlay = False

            if track.properties['overlay previous'] == 'share-y':
                ylim = plot_axis.get_ylim()
            else:
                idx -= skipped_tracks
                plot_axis = axisartist.Subplot(fig, grids[idx, 1])
                fig.add_subplot(plot_axis)
                # turns off the lines around the tracks
                plot_axis.axis[:].set_visible(False)
                # to make the background transparent
                plot_axis.patch.set_visible(False)

                y_axis = plt.subplot(grids[idx, 0])
                y_axis.set_axis_off()

                label_axis = plt.subplot(grids[idx, 2])
                label_axis.set_axis_off()

            plot_axis.set_xlim(start, end)
            track.plot(plot_axis, chrom, start, end)
            track.plot_y_axis(y_axis, plot_axis)
            track.plot_label(label_axis)

            if track.properties['overlay previous'] == 'share-y':
                plot_axis.set_ylim(ylim)

            if not overlay:
                axis_list.append(plot_axis)

        if self.vlines_intval_tree:
            self.plot_vlines(axis_list, chrom, start, end)

        fig.subplots_adjust(wspace=0,
                            hspace=0.0,
                            left=DEFAULT_MARGINS['left'],
                            right=DEFAULT_MARGINS['right'],
                            bottom=DEFAULT_MARGINS['bottom'],
                            top=DEFAULT_MARGINS['top'])

        fig.savefig(file_name, dpi=self.dpi, transparent=False)
        return fig.get_size_inches()
"""
=======================
Simple Axis Direction01
=======================

"""
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist

fig = plt.figure(figsize=(4, 2.5))
ax1 = fig.add_subplot(axisartist.Subplot(fig, 111))
fig.subplots_adjust(right=0.8)

ax1.axis["left"].major_ticklabels.set_axis_direction("top")
ax1.axis["left"].label.set_text("Label")

ax1.axis["right"].label.set_visible(True)
ax1.axis["right"].label.set_text("Label")
ax1.axis["right"].label.set_axis_direction("left")

plt.show()
示例#10
0
    def plot(self, *args):
        """
        Plot all tracks.

        >>> from coolbox.api import *
        >>> frame = XAxis() + XAxis()
        >>> frame.plot("chr1", 100000, 200000)
        >>> frame.plot("chr1:100000-200000")
        """
        if len(args) >= 3:
            chrom, start, end = args[:3]
        elif len(args) >= 1:
            region_str = args[0]
            gr = GenomeRange(region_str)
            chrom, start, end = (gr.chrom, gr.start, gr.end)
        else:
            raise ValueError(
                "Please specify a genomic range in uscs format. For example: 'chr1:100000-200000'"
            )

        tracks_height = self.get_tracks_height()
        self.properties['height'] = sum(tracks_height)

        fig = plt.figure(figsize=cm2inch(self.properties['width'],
                                         self.properties['height']))
        if 'title' in self.properties:
            fig.suptitle(self.properties['title'])

        grids = matplotlib.gridspec.GridSpec(
            len(tracks_height),
            3,
            height_ratios=tracks_height,
            width_ratios=self.properties['width_ratios'],
            wspace=0.01)

        axis_list = []
        for idx, track in enumerate(self.tracks.values()):
            y_ax = plt.subplot(grids[idx, 0])
            y_ax.set_axis_off()

            ax = axisartist.Subplot(fig, grids[idx, 1])
            fig.add_subplot(ax)
            ax.axis[:].set_visible(False)
            ax.patch.set_visible(False)

            label_ax = plt.subplot(grids[idx, 2])
            label_ax.set_axis_off()

            track.label_ax = label_ax
            track.y_ax = y_ax
            try:
                track.plot(ax, chrom, start, end)

            except Exception as e:
                import sys, os
                exc_type, exc_obj, exc_tb = sys.exc_info()
                fname = exc_tb.tb_frame.f_code.co_filename
                log.error("Error occured when plot track:\n"
                          "\ttrack name: {}\n\ttrack type:{}\n"
                          "\tError: {} {}\n"
                          "\toccurred in \"{}\", line {}".format(
                              track.name, type(track), type(e), str(e), fname,
                              exc_tb.tb_lineno))
                log.exception(e)
            # plot coverages
            if hasattr(track, 'coverages'):
                for cov_idx, cov in enumerate(track.coverages):
                    cov.track = track
                    try:
                        cov.plot(ax, chrom, start, end)
                    except Exception as e:
                        log.error(
                            "Error occured when plot track's coverage:\n"
                            "\ttrack name: {}\n\ttrack type:{}\n\tcoverage name: {}\n\tcov type: {}\n"
                            "\tError: {} {}".format(track.name,
                                                    type(track), cov.name,
                                                    type(cov), type(e),
                                                    str(e)))
                        log.exception(e)

            axis_list.append(ax)

        margins = self.properties['margins']
        fig.subplots_adjust(wspace=0,
                            hspace=0.0,
                            left=margins['left'],
                            right=margins['right'],
                            bottom=margins['bottom'],
                            top=margins['top'])

        plt.close()

        return fig
示例#11
0
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist

fig = plt.figure(figsize=(4, 2.5))
ax1 = fig.add_subplot(axisartist.Subplot(fig, "111"))
fig.subplots_adjust(right=0.8)

ax1.axis["left"].major_ticklabels.set_axis_direction("top")
ax1.axis["left"].label.set_text("Label")

ax1.axis["right"].label.set_visible(True)
ax1.axis["right"].label.set_text("Label")
ax1.axis["right"].label.set_axis_direction("left")

plt.show()
示例#12
0
def makeplot(ppe_or_stability, ip=None, **kwds):
    """Plot stuff"""
    if isinstance(ppe_or_stability, PeakStability):
        stability = ppe_or_stability
        ppe = stability.ppe
    else:
        stability = None
        ppe = ppe_or_stability

    if ppe.extracted is None:
        # Makeplot requires a ModelCluster, so whip one up.
        from diffpy.srmise import ModelCluster
        ppe.defaultvars()  # Make sure everything has some setting.  This
        # shouldn't have harmful side effects.
        rangeslice = ppe.getrangeslice()
        x = ppe.x[rangeslice]
        y = ppe.y[rangeslice]
        dy = ppe.effective_dy[rangeslice]
        mcluster = ModelCluster(ppe.initial_peaks, ppe.baseline, x, y, \
                                dy, None, ppe.error_method, ppe.pf)
        ext = mcluster
    else:
        ext = ppe.extracted

    figdict = {}

    # Range along x-axis
    xlo = kwds.get("xlo", ext.r_cluster[0])
    xhi = kwds.get("xhi", ext.r_cluster[-1])

    # Range of PDF to display
    # This is deferred until the defaults can be calculated
    # min_gr
    # max_gr

    # Define heights and interstitial offsets
    # All values in percent of main axis.
    top_offset = kwds.get("top_offset", 0.)
    dg_height = kwds.get("dg_height", 15. if stability is not None else 0.)
    cmp_height = kwds.get("cmp_height", 15. if ip is not None else 7.5)
    datatop_offset = kwds.get("datatop_offset", 3.)
    # <- Data appears here ->
    databottom_offset = kwds.get("databottom_offset", 3.)
    # <- Residual appears here ->
    bottom_offset = kwds.get("bottom_offset", 3.)

    # Style options
    dg_style = kwds.get("dg_style", default_dg_style)
    gobs_style = kwds.get("gobs_style", default_gobs_style)
    gfit_style = kwds.get("gfit_style", default_gfit_style)
    gind_style = kwds.get("gind_style", default_gind_style)
    gres_style = kwds.get("gres_style", default_gres_style)
    ep_style = kwds.get("ep_style", default_ep_style)
    ip_style = kwds.get("ip_style", default_ip_style)

    # Label options
    userxlabel = kwds.get("xlabel", r'r ($\mathrm{\AA}$)')
    userylabel = kwds.get("ylabel", r'G ($\mathrm{\AA^{-2}}$)')
    datalabelx = kwds.get("datalabelx", .04)
    yideal_label = kwds.get("yideal_label", r'ideal')
    yext_label = kwds.get("yext_label", r'found')

    # Other options
    datalabel = kwds.get("datalabel", None)
    dgformatstr = kwds.get("dgformatstr", r'$\delta$g=%f')
    dgformatpost = kwds.get("dgformatpost", None)  #->userfunction(string)
    show_fit = kwds.get("show_fit", True)
    show_individual = kwds.get("show_individual", True)
    fill_individual = kwds.get("fill_individual", True)
    show_observed = kwds.get("show_observed", True)
    show_residual = kwds.get("show_residual", True)
    mask_residual = kwds.get("mask_residual", False)  #-> number
    show_annotation = kwds.get("show_annotation", True)
    scale = kwds.get("scale", 1.)  # Apply a global scaling factor to the data

    # Define the various data which will be plotted
    r = ext.r_cluster
    dr = (r[-1] - r[0]) / len(r)
    rexpand = np.concatenate(
        (np.arange(r[0] - dr, xlo,
                   -dr)[::-1], r, np.arange(r[-1] + dr, xhi + dr, dr)))
    rfine = np.arange(r[0], r[-1], .1 * dr)
    gr_obs = np.array(resample(ppe.x, ppe.y, rexpand)) * scale
    #gr_fit = resample(r, ext.value(), rfine)
    gr_fit = np.array(ext.value(rfine)) * scale
    gr_fit_baseline = np.array(ext.valuebl(rfine)) * scale
    gr_fit_ind = [
        gr_fit_baseline + np.array(p.value(rfine)) * scale for p in ext.model
    ]
    gr_res = np.array(ext.residual()) * scale

    if mask_residual:
        gr_res = np.ma.masked_outside(gr_res, -mask_residual, mask_residual)

    all_gr = []
    if show_fit: all_gr.append(gr_fit)
    #if show_individual: all_gr.extend([gr_fit_baseline, gr_fit_ind])
    if show_individual:
        all_gr.append(gr_fit_baseline)
        if len(gr_fit_ind) > 0:
            all_gr.extend(gr_fit_ind)
    if show_observed: all_gr.append(gr_obs)

    # gr_fit_ind is a list of lists, so use np.min/max
    # The funky bit with scale makes sure that a user-specified value
    # has scale applied to it, without messing up the default values,
    # which are calculated from already scaled quantities.
    min_gr = kwds.get("min_gr",
                      np.min([np.min(gr) for gr in all_gr]) / scale) * scale
    max_gr = kwds.get("max_gr",
                      np.max([np.max(gr) for gr in all_gr]) / scale) * scale

    if show_residual:
        min_res = np.min(gr_res)
        max_res = np.max(gr_res)
    else:
        min_res = 0.
        max_res = 0.

    # Derive various y limits based on all the offsets
    rel_height = 100. - top_offset - dg_height - cmp_height - datatop_offset - databottom_offset - bottom_offset
    abs_height = 100 * ((max_gr - min_gr) + (max_res - min_res)) / rel_height

    yhi = max_gr + (top_offset + dg_height + cmp_height +
                    datatop_offset) * abs_height / 100
    ylo = yhi - abs_height

    yhi = kwds.get("yhi", yhi)
    ylo = kwds.get("ylo", ylo)

    datatop = yhi - (yhi - ylo) * .01 * (top_offset + dg_height + cmp_height)
    datalabeltop = 1 - .01 * (top_offset + dg_height + cmp_height +
                              datatop_offset)
    resbase = ylo + bottom_offset * abs_height / 100 - min_res

    resbase = kwds.get("resbase", resbase)

    fig = kwds.get("figure", plt.gcf())
    fig.clf()
    ax_data = AA.Subplot(fig, 111)
    fig.add_subplot(ax_data)
    figdict["fig"] = fig
    figdict["data"] = ax_data

    # Plot the data, fit, and residual
    if show_observed:
        plt.plot(rexpand, gr_obs, **gobs_style)
    if show_fit:
        plt.plot(rfine, gr_fit, **gfit_style)
    if fill_individual:
        for peak in gr_fit_ind:
            plt.fill_between(rfine, gr_fit_baseline, peak, **gind_style)
    if show_residual:
        plt.plot(r, gr_res + resbase, 'r-', **gres_style)
        plt.plot((xlo, xhi), 2 * [resbase], 'k:')

    # Format ax_data
    plt.xlim(xlo, xhi)
    plt.ylim(ylo, yhi)
    plt.xlabel(userxlabel)
    plt.ylabel(userylabel)
    ax_data.xaxis.set_minor_locator(plt.MultipleLocator(1))
    #ax_data.yaxis.set_minor_locator(plt.MultipleLocator(np.max([1,int((yhi-ylo)/20)])))
    ax_data.yaxis.set_label_position('left')
    ax_data.yaxis.tick_left()
    ax_data.yaxis.set_ticks_position('both')

    # Remove labels above where insets begin
    #ax_data.yaxis.set_ticklabels([str(int(loc)) for loc in ax_data.yaxis.get_majorticklocs() if loc < datatop])
    ax_data.yaxis.set_ticks([
        loc for loc in ax_data.yaxis.get_majorticklocs()
        if (loc < datatop and loc >= ylo)
    ])

    # Dataset label
    if datalabel is not None:
        dl = plt.text(datalabelx,
                      datalabeltop,
                      datalabel,
                      ha='left',
                      va='top',
                      transform=ax_data.transAxes,
                      weight='bold')
    else:
        dl = None
    figdict["datalabel"] = dl

    # Create new x axis at bottom edge of compare inset
    ax_data.axis["top"].set_visible(False)
    ax_data.axis["newtop"] = ax_data.new_floating_axis(
        0, datatop, axis_direction="bottom")  # "top" bugged?
    ax_data.axis["newtop"].toggle(all=False, ticks=True)
    ax_data.axis["newtop"].major_ticks.set_tick_out(True)
    ax_data.axis["newtop"].minor_ticks.set_tick_out(True)

    # New y-axis label, since AxisLabel positions cannot be set manually.
    # The original label is invisible, but we use its (dynamic) x position
    # to update the new label, which we define have the correct y position.
    # A bit of a tradeoff for the nice insets and ability to define new axes.
    newylabel = plt.text(-.1,
                         .5 * (datatop - ylo) / (yhi - ylo),
                         userylabel,
                         ha='center',
                         va='center',
                         rotation='vertical',
                         transform=ax_data.transAxes)
    labeldict[fig] = newylabel  # so we can find the correct text object
    fig.canvas.mpl_connect('draw_event',
                           on_draw)  # original label invisibility and updating

    # Compare extracted (and ideal, if provided) peak positions clearly.
    if cmp_height > 0:
        ax_cmp = inset_axes(ax_data,
                            width="100%",
                            height="%s%%" % cmp_height,
                            loc=2,
                            bbox_to_anchor=(0.,
                                            -.01 * (top_offset + dg_height), 1,
                                            1),
                            bbox_transform=ax_data.transAxes,
                            borderpad=0)

        figdict["cmp"] = ax_cmp
        plt.axes(ax_cmp)
        comparepositions(ext,
                         ip,
                         ep_style=ep_style,
                         ip_style=ip_style,
                         yideal_label=yideal_label,
                         yext_label=yext_label)
        plt.xlim(xlo, xhi)
        ax_cmp.set_xticks([])

    # Show how extracted peak positions change as dg is changed
    if dg_height > 0:

        ax_dg = inset_axes(ax_data,
                           width="100%",
                           height="%s%%" % dg_height,
                           loc=2,
                           bbox_to_anchor=(0, -.01 * top_offset, 1, 1),
                           bbox_transform=ax_data.transAxes,
                           borderpad=0)

        figdict["dg"] = ax_dg
        plt.axes(ax_dg)
        dgkwds = {}
        if "scale" in kwds:
            dgkwds["scale"] = kwds["scale"]
        if "dgmin" in kwds:
            dgkwds["dgmin"] = kwds["dgmin"]
        if "dgmax" in kwds:
            dgkwds["dgmax"] = kwds["dgmax"]
        dgseries(stability, base=0, pmin=r[0], pmax=r[-1], **dgkwds)
        plt.xlim(xlo, xhi)
        ax_dg.xaxis.set_major_locator(plt.NullLocator())
        ax_dg.yaxis.set_major_locator(plt.MaxNLocator(3))
        plt.ylabel(r'$\delta$g')

    # Annotate the actual dg shown
    if show_annotation:
        dg = np.mean(ext.error_cluster) * scale
        dgstr = dgformatstr % dg
        if "dgformatpost" in kwds:  #post-processing on dg annotation
            dgstr = kwds["dgformatpost"](dgstr)

        if len(ext.model) > 0:
            xpos = np.mean([xlo, ext.model[0]["position"]])  # OK for now.
        else:
            xpos = xlo + .1 * (xhi - xlo)
        if dg_height > 0 and cmp_height > 0:
            # Arrow, text in compare distances line
            ylo2, yhi2 = ax_dg.get_ylim()
            if ip is not None:
                ypos = ylo2 - .25 * cmp_height / dg_height * (yhi2 - ylo2)
            else:
                ypos = ylo2 - .5 * cmp_height / dg_height * (yhi2 - ylo2)
            plt.annotate(dgstr,
                         xy=(xlo, dg),
                         xycoords='data',
                         va='center',
                         ha='center',
                         xytext=(xpos, ypos),
                         textcoords='data',
                         size=8,
                         color='green',
                         arrowprops=dict(
                             arrowstyle="->",
                             connectionstyle="angle,angleA=90,angleB=0,rad=10",
                             color="green"))

        elif dg_height > 0:
            # Arrow, and text located somewhere in main plot region
            # Must change axes
            pass
        elif cmp_height > 0:
            # No arrow, text in compare distances line
            # Must change axes
            plt.axes(ax_cmp)
            ylo2, yhi2 = ax_cmp.get_ylim()
            ypos = yhi2 / 2.
            plt.text(xpos,
                     ypos,
                     dgstr,
                     va='center',
                     ha='center',
                     size=8,
                     color='green')
        else:
            # Text only in main plot region
            # Must change axes
            pass

    plt.draw()

    return figdict
示例#13
0
@author: caoxin
"""

import numpy as np
from matplotlib import pyplot as plt
import mpl_toolkits.axisartist as axisartist
import os
os.getcwd()
os.chdir('/Users/caoxin/desktop/thesis')

#%%
import mpl_toolkits.axisartist as axisartist
#创建画布
fig = plt.figure(figsize=(5, 5))
#使用axisartist.Subplot方法创建一个绘图区对象ax
ax = axisartist.Subplot(fig, 111)
#将绘图区对象添加到画布中
fig.add_axes(ax)
#通过set_visible方法设置绘图区所有坐标轴隐藏
ax.axis[:].set_visible(False)

#ax.new_floating_axis代表添加新的坐标轴
ax.axis["x"] = ax.new_floating_axis(0, 0)
#给x坐标轴加上箭头
ax.axis["x"].set_axisline_style("->", size=1.0)
#添加y坐标轴,且加上箭头
ax.axis["y"] = ax.new_floating_axis(1, 0)
ax.axis["y"].set_axisline_style("-|>", size=1.0)
ax.set_xticks([])
ax.set_yticks([])
ax.annotate("$w_1'$",
示例#14
0
def gen_points():
    for i in range(q):
        x = F97(i)
        ys = curve(x)
        if ys is not None:
            y_top, y_bottom = ys
            yield int(x), int(y_top), int(y_bottom)


points = list(gen_points())
print(points)
xs, y_tops, y_bottoms = list(zip(*points))

with plt.xkcd():
    fig = plt.figure(1, figsize=(4, 4), dpi=100)
    ax = AA.Subplot(fig, 111)
    fig.add_subplot(ax)
    ticks = [16 * i for i in range(7)]
    ax.set_xticks(ticks)
    ax.set_yticks(ticks)
    ax.set_xlim(0, 100)
    ax.set_ylim(0, 100)

    ax.axis["right"].set_visible(False)
    ax.axis["top"].set_visible(False)
    for direction in ["left", "bottom"]:
        ax.axis[direction].set_axisline_style("-|>")

    ax.scatter(xs, y_tops, marker='.', c='black')
    ax.scatter(xs, y_bottoms, marker='.', c='black')
    ax.set_title(r'$Y^2 = X^3 + 4$ (mod 97)')
pol_interval = np.array([0, 2 * np.pi])  # interpolation interval
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

# calculate the values of interpolation function
x_node = np.linspace(pol_interval[0], pol_interval[1],
                     num_pl_node)  # nodes of interpolation
y_value = f(x_node)  # {f(x_i)}
x_plot = np.linspace(x_node.min(), x_node.max(),
                     num=100)  # points for plot on the x-axis
dq = dq_producer(x_node, y_value)  # an array of difference quotients
pv_plot = pol_value(
    dq, x_node, x_plot)  # values of interpolation function at points for plot

# config the figure
fig = plt.figure(num=1)
ax = ax_ar.Subplot(fig, 111)
fig.add_axes(ax)
ax.axis["bottom"].set_axisline_style("->", size=1.5)
ax.axis["left"].set_axisline_style("->", size=1.5)
ax.axis["top"].set_visible(False)
ax.axis["right"].set_visible(False)
plt.xlabel('x')
plt.ylabel('y')

# draw figures
plt.plot(x_plot, f(x_plot), label='f(x)')
plt.plot(x_plot, pv_plot, color='red', linestyle='--', label='P(x)')
plt.scatter(x_node, y_value)
plt.legend([f_text, 'P(x)', 'nodes of interpolation'])

plt.show()
"""
==================
Simple Axisartist1
==================

"""
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as AA

fig = plt.figure(1)
fig.subplots_adjust(right=0.85)
ax = AA.Subplot(fig, 1, 1, 1)
fig.add_subplot(ax)

# make some axis invisible
ax.axis["bottom", "top", "right"].set_visible(False)

# make an new axis along the first axis axis (x-axis) which pass
# through y=0.
ax.axis["y=0"] = ax.new_floating_axis(nth_coord=0,
                                      value=0,
                                      axis_direction="bottom")
ax.axis["y=0"].toggle(all=True)
ax.axis["y=0"].label.set_text("y = 0")

ax.set_ylim(-2, 4)

plt.show()
示例#17
0
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist

fig = plt.figure(figsize=(3, 2.5))
fig.subplots_adjust(top=0.8)

ax = axisartist.Subplot(fig, "111")
fig.add_axes(ax)

ax.set_ylim(-0.1, 1.5)
ax.set_yticks([0, 1])
ax.axis[:].set_visible(False)

ax.axis["x"] = ax.new_floating_axis(1, 0.5)
ax.axis["x"].set_axisline_style("->", size=1.5)
ax.axis["x"].set_axis_direction("left")

plt.show()
示例#18
0
def draw_figure(cars, t_adjust_done, t_pass_done):
    # 通过set_visible方法设置绘图区的顶部及右侧坐标轴隐藏
    t_sequence = [ i / t_adjust_done * Car.t_expected for i in list(range(len(cars[0].x_sequence))) ]
    for car in cars:
        plt.figure()
        plt.plot(t_sequence, car.x_sequence)
        plt.savefig('figures\\' + car.name + 'x.png', format='png')
        plt.close()
        plt.figure()
        plt.plot(t_sequence, car.v_sequence)
        plt.savefig('figures\\' + car.name + 'v.png', format='png')
        plt.close()
        plt.figure()
        plt.plot(t_sequence, car.a_sequence)
        plt.savefig('figures\\' + car.name + 'a.png', format='png')
        plt.close()
    fig = plt.figure()
    ax = axisartist.Subplot(fig, 111)
    fig.add_axes(ax)
    ax.axis["top"].set_visible(False)
    ax.axis["right"].set_visible(False)
    ax.axis["left"].set_axisline_style("->", size=1.0)
    ax.axis["bottom"].set_axisline_style("->", size=1.0)
    plt.plot(t_sequence, cars[0].x_sequence)
    plt.plot(t_sequence, cars[1].x_sequence)
    plt.plot(t_sequence, cars[2].x_sequence)
    plt.plot(t_sequence, cars[3].x_sequence)
    plt.plot(t_sequence, cars[4].x_sequence)
    plt.vlines(Car.t_expected, min(car.x_sequence), max(car.x_sequence), color="k",linestyles='--')  # 竖线
    plt.vlines(t_pass_done / t_adjust_done * Car.t_expected, min(car.x_sequence), max(car.x_sequence), color="k", linestyles="--")  # 竖线
    plt.legend(["A", "B", "C", "D", "E"])
    plt.xlabel('time')
    plt.ylabel('distance')
    plt.ylim(0, max(car.x_sequence))
    plt.text(Car.t_expected - 1.5, 5, "t_a")
    plt.text(t_pass_done / t_adjust_done * Car.t_expected - 1.5, 5, "t_p")
    ax = plt.gca()
    ax.spines['top'].set_color('none')
    ax.spines['right'].set_color('none')
    plt.savefig('figures\\x_all.png', format='png')
    plt.close()
    fig = plt.figure()
    ax = axisartist.Subplot(fig, 111)
    fig.add_axes(ax)
    ax.axis["top"].set_visible(False)
    ax.axis["right"].set_visible(False)
    ax.axis["left"].set_axisline_style("->", size=1.0)
    ax.axis["bottom"].set_axisline_style("->", size=1.0)
    plt.plot(t_sequence, cars[0].v_sequence)
    plt.plot(t_sequence, cars[1].v_sequence)
    plt.plot(t_sequence, cars[2].v_sequence)
    plt.plot(t_sequence, cars[3].v_sequence)
    plt.plot(t_sequence, cars[4].v_sequence)
    plt.legend(["A", "B", "C", "D", "E"])
    plt.xlabel('time')
    plt.ylabel('velocity')
    plt.savefig('figures\\v_all.png', format='png')
    plt.close()
    fig = plt.figure()
    ax = axisartist.Subplot(fig, 111)
    fig.add_axes(ax)
    ax.axis["top"].set_visible(False)
    ax.axis["right"].set_visible(False)
    ax.axis["left"].set_axisline_style("->", size=1.0)
    ax.axis["bottom"].set_axisline_style("->", size=1.0)
    plt.plot(t_sequence, cars[0].a_sequence)
    plt.plot(t_sequence, cars[1].a_sequence)
    plt.plot(t_sequence, cars[2].a_sequence)
    plt.plot(t_sequence, cars[3].a_sequence)
    plt.plot(t_sequence, cars[4].a_sequence)
    plt.legend(["A", "B", "C", "D", "E"])
    plt.xlabel('time')
    plt.ylabel('accelorate')
    plt.savefig('figures\\a_all.png', format='png')
    plt.close()
示例#19
0
文件: plot.py 项目: vbgl/fiat
def plotbench(grouped):
    linum = 0
    colors = OrderedDict([("ether", "orange"), ("arp", "yellow"),
                          ("ip", "green"), ("tcp", "blue"), ("udp", "purple")])
    # labels = OrderedDict([("ether", "Ethernet header"),
    #                       ("arp",   "ARP header & payload"),
    #                       ("ip",    "IPv4 header"),
    #                       ("tcp",   "TCP header & payload"),
    #                       ("udp",   "UDP header & payload")])
    labels = OrderedDict([("ether", "Ethernet"), ("arp", "ARP"),
                          ("ip", "IPv4"), ("tcp", "TCP"), ("udp", "UDP")])

    rcParams.update({
        "font.size": 9,
        "legend.fontsize": 8,
        "font.family": "Ubuntu Mono",
        "axes.titlesize": "medium",
        "xtick.labelsize": "small",
        "ytick.labelsize": "small",
        # "text.usetex": True,
        # "text.latex.unicode": True,
        "savefig.bbox": "tight",
        "savefig.pad_inches": 0.05
    })

    ylabels = []
    fig = pyplot.figure(1, figsize=(4, 2.75))
    fig.subplots_adjust(left=0.5, hspace=0.7)
    ax = axisartist.Subplot(fig, 111)
    fig.add_subplot(ax)

    THICKNESS = 1
    LINE_HEIGHT = THICKNESS * 1.3
    for name, g in grouped.items():
        # ylabels.append(name.upper())
        for direction, g in g.items():
            size = list(set(size for (_, (size, _)) in g.items()))[0]
            ylabels.append("{} {}".format(name.upper(), direction))  #  ({}b)
            # name = " " * len(name) # Omit names on next iterations
            for kind, (sz, measurements) in g.items():
                assert sz == size
                ylabels.append("  {} ({}b)".format(kind, sz))
                width_acc = 0
                linum = (len(ylabels) - 1) * LINE_HEIGHT
                for proto, width, dwlow, dwhigh in measurements:
                    # print(width, dwlow, dwhigh)
                    color = HEX[colors[proto]]
                    bottom = -linum
                    pyplot.errorbar(
                        [width_acc + width],
                        [bottom],  # xerr=[[-dwlow], [dwhigh]],
                        ecolor=color[2],
                        fmt='')
                    pyplot.barh(bottom, [width],
                                THICKNESS,
                                left=[width_acc],
                                color=color[0],
                                edgecolor=color[2],
                                linewidth=0.5,
                                label=proto)
                    width_acc += width

    ax.set_ylim((-len(ylabels) * LINE_HEIGHT, 0))
    # ax.set_xlim((0, 4.75))
    ax.set_yticks([-n * LINE_HEIGHT for n in range(len(ylabels))])
    ax.set_yticklabels(ylabels)
    ax.set_xlabel("Single-packet processing time (µs)")
    # ax.set_xticks([x * 0.5 for x in range(5 * 2)])
    ax.axis["left"].major_ticklabels.set_ha("left")
    ax.axis["left"].major_ticks.set_visible(False)
    ax.axis["top"].major_ticks.set_visible(False)
    ax.axis["right"].major_ticks.set_visible(False)
    ax.axis["bottom"].major_ticks.set_ticksize(2)

    legend_patches = [
        patches.Patch(facecolor=HEX[color][0],
                      edgecolor=HEX[color][2],
                      label=labels[proto]) for proto, color in colors.items()
    ]
    pyplot.legend(handles=legend_patches, loc="upper right", fontsize=8)

    return fig
示例#20
0
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist
#创建画布
fig = plt.figure(figsize=(8, 8))
#使用axisartist.Subplot方法创建一个绘图区对象ax
ax = axisartist.Subplot(fig, 111)
#将绘图区对象添加到画布中
fig.add_axes(ax)

#通过set_visible方法设置绘图区所有坐标轴隐藏
ax.axis[:].set_visible(False)

#ax.new_floating_axis代表添加新的坐标轴
ax.axis["x"] = ax.new_floating_axis(0, 0)
#给x坐标轴加上箭头
ax.axis["x"].set_axisline_style("->", size=1.0)
#添加y坐标轴,且加上箭头
ax.axis["y"] = ax.new_floating_axis(1, 0)
ax.axis["y"].set_axisline_style("-|>", size=1.0)
#设置x、y轴上刻度显示方向
ω = np.pi
a = 2
φ = np.pi / 3
t = np.linspace(-np.pi, np.pi, 1000)
x1 = a * np.cos(ω * t + φ)
#设置坐标轴的文字标签

ax.set_title("X=Acos(ωt+φ)")
plt.xticks([])
plt.yticks([])
示例#21
0
    def create_axes(self, rect=111):
        """
        Create a special AxisArtist to overlay grid coordinates.

        Much of this taken from the examples here:
        http://matplotlib.org/mpl_toolkits/axes_grid/users/axisartist.html
        """

        # from curved coordinate to rectlinear coordinate.
        def tr(x, y):
            x, y = np.asarray(x), np.asarray(y)
            return self(x, y)

        # from rectlinear coordinate to curved coordinate.
        def inv_tr(x, y):
            x, y = np.asarray(x), np.asarray(y)
            return self(x, y, inverse=True)

        # Cycle the coordinates
        extreme_finder = angle_helper.ExtremeFinderCycle(20, 20)

        # Find a grid values appropriate for the coordinate.
        # The argument is a approximate number of grid lines.
        grid_locator1 = angle_helper.LocatorD(9, include_last=False)
        #grid_locator1 = angle_helper.LocatorD(8,include_last=False)
        grid_locator2 = angle_helper.LocatorD(6, include_last=False)

        # Format the values of the grid
        tick_formatter1 = self.create_tick_formatter()
        tick_formatter2 = angle_helper.FormatterDMS()

        grid_helper = GridHelperCurveLinear(
            (tr, inv_tr),
            extreme_finder=extreme_finder,
            grid_locator1=grid_locator1,
            grid_locator2=grid_locator2,
            tick_formatter1=tick_formatter1,
            tick_formatter2=tick_formatter2,
        )

        fig = plt.gcf()
        if rect is None:
            # This doesn't quite work. Need to remove the existing axis...
            rect = plt.gca().get_position()
            plt.gca().axis('off')
            ax = axisartist.Axes(fig, rect, grid_helper=grid_helper)
            fig.add_axes(ax)
        else:
            ax = axisartist.Subplot(fig, rect, grid_helper=grid_helper)
            fig.add_subplot(ax)

        ## Coordinate formatter
        def format_coord(x, y):
            return 'lon=%1.4f, lat=%1.4f' % inv_tr(x, y)

        ax.format_coord = format_coord
        ax.axis['left'].major_ticklabels.set_visible(True)
        ax.axis['right'].major_ticklabels.set_visible(False)
        ax.axis['bottom'].major_ticklabels.set_visible(True)
        ax.axis['top'].major_ticklabels.set_visible(True)

        ax.set_xlabel("Right Ascension")
        ax.set_ylabel("Declination")
        #self.set_axes_limits()

        self.axisartist = ax
        return fig, ax
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist
import matplotlib.ticker as ticker

x = np.linspace(-5, 5, 50)
y1 = np.sin(x)
y2 = np.sin(x + 1)

fig = plt.figure()
ax = axisartist.Subplot(fig, 211)
fig.add_axes(ax)

ax.axis[:].set_visible(False)
ax.axis["x"] = ax.new_floating_axis(0, 0)
ax.axis["x"].set_axisline_style("->", size=1.0)

ax.axis["y"] = ax.new_floating_axis(1, 0)
ax.axis["y"].set_axisline_style("->", size=1.0)
ax.axis["y"].set_axis_direction("left")
ax.xaxis.set_major_locator(ticker.NullLocator())
ax.yaxis.set_major_locator(ticker.NullLocator())
ax.set_xlim(-5, 5)
ax.set_ylim(-2, 2)
plt.title('$x[n]$')
plt.stem(x, y1)

ax = axisartist.Subplot(fig, 212)
fig.add_axes(ax)

ax.axis[:].set_visible(False)
示例#23
0
def coordinate_dot(x_min,
                   x_max,
                   y_min,
                   y_max,
                   w_res,
                   h_res,
                   y_flip=False,
                   dst_dir="."):
    '''
    y_flip=True 代表 原點在左上角,image coordinate 會用到
    '''
    Check_dir_exist_and_build(dst_dir)  ### 建立 dst_dir

    x = np.tile(np.reshape(np.linspace(x_min, x_max, w_res), [1, w_res]),
                [h_res, 1])
    y = np.tile(np.reshape(np.linspace(y_min, y_max, h_res), [h_res, 1]),
                [1, w_res])
    if (y_flip): y = y_max - y
    # y_t = np.expand_dims(y, axis=-1)
    # x_t = np.expand_dims(x, axis=-1)
    # meshgrid = np.concatenate([y_t, x_t], axis=-1)
    # print("meshgrid.shape", meshgrid.shape)

    fig, ax = plt.subplots(nrows=1, ncols=1)
    fig.tight_layout()
    fig.set_size_inches(8, 8.1)
    ax.scatter(x, y, s=1)
    ax.set_xticks(x[0, ::2])
    ax.set_yticks(y[::2, 0])
    # ax.set_xlabel('X LABEL')
    # ax.xaxis.set_label_position('top')
    ax.xaxis.tick_top()
    ### https://blog.csdn.net/qq_39429714/article/details/95988703
    # ax.spines['top'].set_visible(False)
    # ax.spines['left'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.invert_yaxis()
    save_string = f"coord_x={x_min}~{x_max}, y={y_min}~{y_max}, w_res={w_res}, h_res={h_res}"
    plt.savefig(dst_dir + "/" + save_string)
    plt.savefig(dst_dir + "/" + f"{save_string}_透明", transparent=True)
    # plt.show()
    '''
    和上面的效果幾乎差不多,本來是希望能夠畫出漂亮的 x,y 軸才用下面的 axisartist,
    但後來發現 y軸方向 改不了! 所以幾乎就沒用了!
    不過也是個還不錯的例子就保留下來囉!
    '''
    import mpl_toolkits.axisartist as AA
    fig2 = plt.figure()
    axAA = AA.Subplot(fig2, 111)
    fig2.add_axes(axAA)
    fig2.set_size_inches(8, 8)
    axAA.scatter(x, y, s=1)
    fig.tight_layout()
    axAA.set_xticks(x[0, ::2])
    axAA.set_yticks(y[::2, 0])
    axAA.set_ylim(y_max, y_min)  ### 用ylim設反 也沒辦法讓箭頭 往下 QAQ
    ### https://blog.csdn.net/A_Z666666/article/details/80400858
    ### https://blog.csdn.net/COCO56/article/details/100173824
    axAA.axis["top"].set_axisline_style("-|>", size=2.5)
    axAA.axis["left"].set_axisline_style("-|>", size=2.5)
    axAA.axis["left"].set_ticklabel_direction("-")
    axAA.axis["bottom"].set_visible(False)
    axAA.axis["right"].set_visible(False)
    axAA.axis["top"].major_ticklabels.set_visible(True)
    axAA.axis["bottom"].major_ticklabels.set_visible(False)
    # axAA.invert_yaxis()
    # print(dir(axAA.axis["left"  ]))
    # print(dir(axAA))
    # print(axAA.yaxis_inverted())
    plt.show()
示例#24
0
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist


def x(t):
    return np.exp(t) * np.cos(8 * t - 200)


fig = plt.figure(figsize=(10, 8), dpi=80)
ax1 = axisartist.Subplot(fig, 111)
fig.add_axes(ax1)

ax1.axis[:].set_visible(False)
ax1.axis["x"] = ax1.new_floating_axis(0, 0)

ax1.axis["x"].set_axisline_style("->", size=1.0)
ax1.axis["y"] = ax1.new_floating_axis(1, 0)
ax1.axis["y"].set_axisline_style("->", size=1.0)
ax1.axis["x"].set_axis_direction("top")
ax1.axis["y"].set_axis_direction("right")

plt.xlim(-6, 6)
plt.ylim(-100, 100)

t = np.arange(-6, 6, 0.01)
plt.plot(t, x(t), 'r-')
plt.title('x(t)=cos(ωt+θ)*e**(σt)')
plt.xlabel('t')
plt.show()
示例#25
0
    def plot(self, file_name, chrom, start, end, title=None,
             h_align_titles='left', decreasing_x_axis=False):
        track_height = self.get_tracks_height(start_region=start,
                                              end_region=end)

        if self.fig_height:
            fig_height = self.fig_height
        else:
            fig_height = sum(track_height) / \
                (DEFAULT_MARGINS['top'] - DEFAULT_MARGINS['bottom'])

        log.debug(f"Figure size in cm is {self.fig_width} x {fig_height}."
                  f" Dpi is set to {self.dpi}\n")
        fig = plt.figure(figsize=self.cm2inch(self.fig_width, fig_height))

        fig.subplots_adjust(wspace=0, hspace=0.0,
                            left=DEFAULT_MARGINS['left'],
                            right=DEFAULT_MARGINS['right'],
                            bottom=DEFAULT_MARGINS['bottom'],
                            top=DEFAULT_MARGINS['top'])

        if title:
            fig.suptitle(title)

        grids = matplotlib.gridspec.GridSpec(len(track_height), 3,
                                             height_ratios=track_height,
                                             width_ratios=self.width_ratios,
                                             wspace=0.01)
        axis_list = []
        # skipped_tracks is the count of tracks that have the
        # 'overlay_previous' parameter and should be skipped
        skipped_tracks = 0
        plot_axis = None
        for idx, track in enumerate(self.track_obj_list):
            log.info(f"plotting {track.properties['section_name']}")

            if track.properties['overlay_previous'] in ['yes', 'share-y']:
                overlay = True
                skipped_tracks += 1
            else:
                overlay = False

            if track.properties['overlay_previous'] == 'share-y':
                ylim = plot_axis.get_ylim()
            else:
                idx -= skipped_tracks
                plot_axis = axisartist.Subplot(fig, grids[idx, 1])
                fig.add_subplot(plot_axis)
                # turns off the lines around the tracks
                plot_axis.axis[:].set_visible(False)
                # to make the background transparent
                plot_axis.patch.set_visible(False)
                if not overlay:
                    y_axis = plt.subplot(grids[idx, 0])
                    y_axis.set_axis_off()

                    label_axis = plt.subplot(grids[idx, 2])
                    label_axis.set_axis_off()
                    # I get the width of the label_axis to be able to wrap the
                    # labels when right or center aligned.
                    width_inch = label_axis.get_window_extent().width
                    width_dpi = width_inch * self.dpi / fig.dpi

            if decreasing_x_axis:
                plot_axis.set_xlim(end, start)
            else:
                plot_axis.set_xlim(start, end)
            track.plot(plot_axis, chrom, start, end)
            track.plot_y_axis(y_axis, plot_axis)
            track.plot_label(label_axis, width_dpi=width_dpi,
                             h_align=h_align_titles)

            if track.properties['overlay_previous'] == 'share-y':
                plot_axis.set_ylim(ylim)

            if not overlay:
                axis_list.append(plot_axis)

        if self.vlines_intval_tree:
            self.plot_vlines(axis_list, chrom, start, end)

        fig.savefig(file_name, dpi=self.dpi, transparent=False)
        return fig.get_size_inches()
示例#26
0
    # a = r * np.cos(theta)
    # b = r * np.sin(theta)
    # b = -abs(b)

    # # 检查交点
    # for i in range(0, 301):
    #     for j in range(0, theta.shape[0]):
    #         if round(x[i], 3) == round(a[j], 3):
    #             if (abs(p1(x[i])) - abs(b[j])) < 0:
    #                 print('intersection:', x[i])
    #                 print(yvals[i])
    #                 print(b[j])

    # 坐标轴移到中间
    fig = plt.figure('Sine Wave', (10, 8))
    ax = axisartist.Subplot(fig, 1, 1, 1)
    fig.add_axes(ax)
    ax.axis[:].set_visible(False)
    ax.axis["x"] = ax.new_floating_axis(0, 0)
    ax.axis["y"] = ax.new_floating_axis(1, 0)
    ax.axis["x"].set_axis_direction('top')
    ax.axis["y"].set_axis_direction('left')

    # plot
    plot0 = plt.plot(x, k, color='y', label='65 degree line')
    plot1 = plt.plot(x, y, color='g', label='data')
    plot2 = plt.plot(x, fit_value, color='r', label='polyfit values')
    plot2_1 = plt.plot(x, fit_value2, color='orange', label='bezier')
    plot3 = plt.plot(x_circle, y_circle, color='b', label='circle benchmark')
    plt.savefig("filename.png")
    fig.legend(loc='lower left')
示例#27
0
    def create_main_frame(self):
        self.main_frame = QWidget()
        
        plot_frame = QWidget()
        
        self.dpi = 100
        self.fig = Figure((6.0, 4.0), dpi=self.dpi, facecolor='w', edgecolor='k')
        self.canvas = FigureCanvas(self.fig)
        #self.canvas.setParent(self.main_frame)
        self.cidpress = self.fig.canvas.mpl_connect('pick_event', self.on_pick)

        self.axes = AA.Subplot(self.fig,1,1,1)
        self.fig.add_subplot(self.axes)
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
        
        log_label = QLabel("Spectra:")
        self.series_list_view = QTreeView()
        self.series_list_view.setModel(self.series_list_model)
        self.series_list_view.setDragDropMode(QAbstractItemView.InternalMove)

        #Checkboxes to control plotting display
        self.param_cb = QCheckBox("Show Parameters")
        self.param_cb.setChecked(False)
        self.param_cb.stateChanged.connect(self.on_show)

        self.autoscale_cb = QCheckBox("&Autoscale")
        self.autoscale_cb.setChecked(True)
        self.autoscale_cb.stateChanged.connect(self.on_show)

        self.normalize_cb = QCheckBox("&Normalize")
        self.normalize_cb.setChecked(False)
        self.normalize_cb.stateChanged.connect(self.on_show)

        self.NE_cb = QCheckBox("&NE(E)")
        self.NE_cb.setChecked(True)
        self.NE_cb.stateChanged.connect(self.on_show)

        self.dNE_cb = QCheckBox("&dNE(E)/dE")
        self.dNE_cb.setChecked(False)
        self.dNE_cb.stateChanged.connect(self.on_show)

        self.smoothing_le = QLineEdit("2")
        self.smoothing_le.textChanged.connect(self.on_show)

        self.BG_cb = QCheckBox("&Show Background")
        self.BG_cb.setChecked(True)
        self.BG_cb.stateChanged.connect(self.on_show)

        self.stacked_cb = QCheckBox("&Stacked")
        self.stacked_cb.setChecked(True)
        self.stacked_cb.stateChanged.connect(self.on_show)

        #plotting display controls layout
        cb_hbox1 = QHBoxLayout()
        cb_hbox2 = QHBoxLayout()
        cb_hbox3 = QHBoxLayout()
        cb_vbox = QVBoxLayout()
        cb_hbox1.addWidget(self.param_cb)
        cb_hbox1.addWidget(self.autoscale_cb)
        cb_hbox2.addWidget(self.NE_cb)
        cb_hbox2.addWidget(self.dNE_cb)
        cb_hbox2.addWidget(self.smoothing_le)
        cb_hbox3.addWidget(self.normalize_cb)
        cb_hbox3.addWidget(self.BG_cb)
        cb_hbox3.addWidget(self.stacked_cb)
        cb_vbox.addLayout(cb_hbox1)
        cb_vbox.addLayout(cb_hbox2)
        cb_vbox.addLayout(cb_hbox3)
        
        #select fit types to add when clicking
        self.peakTypeGroup = QGroupBox("Fit Type to Add")
        self.sPeakRadio = QRadioButton("&s")
        self.pPeakRadio = QRadioButton("&p")
        self.dPeakRadio = QRadioButton("&d")
        self.fPeakRadio = QRadioButton("&f")
        self.tougaardRadio = QRadioButton("&Tougaard")
        self.tougaard3Radio = QRadioButton("&Tougaard3")
        self.sloped_arctanRadio = QRadioButton("&arctan")
        self.tougaardRadio.setChecked(True)

        #layout fitting types
        peak_vbox = QVBoxLayout()
        bg_vbox = QVBoxLayout()
        fit_hbox = QHBoxLayout()
        peak_vbox.addWidget(self.sPeakRadio)
        peak_vbox.addWidget(self.pPeakRadio)
        peak_vbox.addWidget(self.dPeakRadio)
        peak_vbox.addWidget(self.fPeakRadio)
        bg_vbox.addWidget(self.tougaardRadio)
        bg_vbox.addWidget(self.tougaard3Radio)
        bg_vbox.addWidget(self.sloped_arctanRadio)
        bg_vbox.addStretch(1)
        fit_hbox.addLayout(peak_vbox)
        fit_hbox.addLayout(bg_vbox)
        self.peakTypeGroup.setLayout(fit_hbox)

        #action buttons
        self.button_clear_peaks = QPushButton("&Clear Peaks")
        self.button_clear_peaks.clicked.connect(self.clear_peaks)
        self.button_clear_peaks.setShortcut("Ctrl+C")

        self.button_optimize_peaks = QPushButton("Optimize &Peaks")
        self.button_optimize_peaks.clicked.connect(self.optimize_peaks)
        self.button_optimize_peaks.setShortcut("Ctrl+P")

        self.button_clear_bg = QPushButton("Clear &BG")
        self.button_clear_bg.clicked.connect(self.clear_bg)
        self.button_clear_bg.setShortcut("Ctrl+B")

        self.button_adjust_offset = QPushButton("&Adjust Offset")
        self.button_adjust_offset.clicked.connect(self.adjust_offset)
        self.button_adjust_offset.setShortcut("Ctrl+A")

        self.button_write_fits = QPushButton("&Write Fits")
        self.button_write_fits.clicked.connect(self.write_fits)
        self.button_write_fits.setShortcut("Ctrl+W")

        self.button_load_fits = QPushButton("&Load Fits")
        self.button_load_fits.clicked.connect(self.load_fits)
        self.button_load_fits.setShortcut("Ctrl+L")

        self.button_write_summary = QPushButton("&Export Summary")
        self.button_write_summary.clicked.connect(self.write_summary_csv)
        self.button_write_summary.setShortcut("Ctrl+E")

        #action buttons layout
        mods_box = QGridLayout()
        mods_box.addWidget(self.button_optimize_peaks,0,0)
        mods_box.addWidget(self.button_clear_peaks,0,1)
        mods_box.addWidget(self.button_clear_bg,0,2)
        mods_box.addWidget(self.button_adjust_offset,1,0)
        mods_box.addWidget(self.button_write_fits,1,1)
        mods_box.addWidget(self.button_load_fits,1,2)
        mods_box.addWidget(self.button_write_summary,3,1)

        left_vbox = QVBoxLayout()
        left_vbox.addWidget(self.canvas)
        left_vbox.addWidget(self.mpl_toolbar)
        left_widget = QWidget()
        left_widget.setLayout(left_vbox)

        right_vbox = QVBoxLayout()
        right_vbox.addWidget(log_label)
        right_vbox.addWidget(self.series_list_view,stretch=1)
        right_vbox.addLayout(cb_vbox)
        right_vbox.addWidget(self.peakTypeGroup)
        right_vbox.addLayout(mods_box)
        right_widget = QWidget()
        right_widget.setLayout(right_vbox)
        
        self.main_frame = QSplitter()
        self.main_frame.addWidget(left_widget)
        self.main_frame.addWidget(right_widget)

        self.setCentralWidget(self.main_frame)