Пример #1
0
def run(parser):
    x1 = []
    y1 = []
    z1 = []
    args = parser.parse_args()
    subprocess.call(
        "bedtools intersect -a  %s -b %s -wo |grep -v e|bedtools groupby -i - -g 1,2,3,4 -c 8,9 -o mean,sum |awk '{print $1,$2,$3,$4,$5,$6/($3-$2)}'| sed 's/ /\t/g' > DMRs-Histone.diff"
        % (args.DMRs, args.DiffHistPeaks),
        shell=True)

    try:
        formatfile1 = open("DMRs-Histone.diff", 'r')
    except IOError:
        print >> sys.stderr, 'cannot open', filename
        raise SystemExit
    for line in formatfile1:
        rows = line.strip().split("\t")
        x1.append(rows[3])
        y1.append(rows[4])
        z1.append(rows[5])
    arrayx = [float(m) for m in x1]
    arrayy = [np.log2(float(m)) for m in y1]
    arrayz = [float(m) for m in z1]

    mean_x = np.mean(arrayx)
    mean_y = np.mean(arrayy)
    mean_z = np.mean(arrayz)

    #print mean_x
    #print mean_y
    #print mean_z

    fig = plt.figure()
    #ax = fig.gca(projection='3d')
    #for c,m in [('r','o'),('b','^')]:
    #   ax = fig.gca(projection='3d')
    #ax = fig.add_subplot(111, projection='3d')
    ax = Axes3D(fig)
    ax.scatter(arrayx, arrayy, arrayz, c='b', marker='^')
    ax.scatter(arrayx, arrayy, zs=0, marker='x', c='r', zdir='z')
    ax.scatter(arrayx, arrayz, zs=4.5, marker='x', c='k', zdir='y')
    ax.scatter(arrayy, arrayz, zs=-1, marker='x', c='g', zdir='x')
    #ax.plot(arrayx, arrayz, 'r+', zdir='y', zs=4.5)
    ax.plot(arrayy, arrayz, 'g+', zdir='x', zs=-1)
    l1 = a3d.Line3D((0, 0, 0), (4, 0, 0), (0, 0, 0), c='k', ls='--')
    l2 = a3d.Line3D((0, 0, -0.5), (0, 0, 0), (0, 0, 0), c='g', ls='--')
    l3 = a3d.Line3D((0, 0, 0), (0, 0, 0), (0, 0.2, 0), c='r', ls='--')
    ax.add_line(l1)
    ax.add_line(l2)
    ax.add_line(l3)
    ax.add_line(l3)
    ax.set_xlim([-1, 1])
    ax.set_ylim([-12.5, 4.5])
    ax.set_zlim([0, 1])

    ax.set_xlabel('mCG/CG(WT-3aKO)')
    ax.set_ylabel('H3K4me3.Log2(WT/3aKO)')
    ax.set_zlabel('Overlap Ratio')
    fig.savefig(args.outFile + ".png")
Пример #2
0
def plot_signals_3d(signals, filepath):
    xlim = [-1, 7]

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1, projection='3d')
    ax.view_init(20, 250)
    for i in range(signals.shape[0]):
        depth = 0.2 * (i - 1)
        for j in range(signals.shape[1]):
            line = art3d.Line3D(*zip((j, depth, 0), (j, depth, signals[i, j])),
                                marker='o',
                                markevery=(1, 1),
                                linestyle='-',
                                color=COLORS[i])
            ax.add_line(line)
    plt.xlim(xlim)
    plt.xlabel('$n$')
    # plt.ylim([-1.1, 1.1])
    ax.set_yticklabels([])
    ax.set_ylim([-0.4, 0.5])
    ax.set_zlim([0, 0.6])
    # ax.set_zticks(np.arange(-1,1.1,0.25))
    # ax.set_zticklabels(['-1','','','','0','','','','1'])

    plt.savefig(filepath.absolute(), bbox_inches='tight', dpi=300)
Пример #3
0
def draw_line3D(origin=[(0, 0, 0)],
                pmom=[(1, 1, 1)],
                color='red',
                ls='-',
                lw=2.0):

    lines = []

    #print pmom
    for o, p in zip(origin, pmom):
        #x1 = p[0]
        #y1 = p[1]
        #z1 = p[2]
        x1 = p[2]
        y1 = p[0]
        z1 = p[1]
        #print x1,y1,z1
        line = a3.Line3D((o[0], x1), (o[1], y1), (o[0], z1),
                         lw=lw,
                         ls=ls,
                         alpha=0.9,
                         color=color,
                         markeredgecolor=color)
        lines.append(line)

    return lines
Пример #4
0
def plot_line(line):
    line_width = 2.0
    x1x2, y1y2, z1z2, color = line
    ax.add_line(art3d.Line3D(x1x2, y1y2, z1z2, lw=line_width, color=color))
    box = {'alpha': 0.1, 'pad': 1}
    text_args = {'size': 10, 'zorder': 1, 'bbox': box}
    ax.text(x1x2[0], y1y2[0], z1z2[0], '0', color='black', **text_args)
Пример #5
0
def stemcf3d(gridu, gridv, phase, modulus, darken=None, fig=None, markerp="o", **kwargs):
    r"""Stemplot the modulus of a complex valued function :math:`f:I\times I -> \mathbb{C}` together with its
    phase in a color coded fashion. Additional keyword arguments are passed to the plot function.

    :param gridu: The x components of the grid nodes of the real domain grid :math:`\Gamma`
    :param gridv: The y components of the grid nodes of the real domain grid :math:`\Gamma`
    :param phase: The phase of the complex domain result :math:`f(\Gamma)`
    :param modulus: The modulus of the complex domain result :math:`f(\Gamma)`
    :param darken: Whether to take into account the modulus of the data to darken colors.
    :param fig: The figure instance used for plotting.
    :param markerp: The shape of the stemmed markers.
    """
    # Color mapping
    rgb_colors = squeeze(color_map(gridv, phase=phase, modulus=modulus, darken=darken))

    # Plot to the given axis instance or retrieve the current one
    if fig is None:
        fig = gcf()

    axes = fig.add_subplot(1, 1, 1, projection='3d')

    for ui, vi, wi, col in zip(gridu, gridv, modulus, rgb_colors):
        line = art3d.Line3D(*list(zip((ui, vi, 0), (ui, vi, wi))), marker=markerp, markevery=(1, 1), color=col)
        axes.add_line(line)

    axes.set_xlim3d(real(gridu).min(), real(gridu).max())
    axes.set_ylim3d(real(gridv).min(), real(gridv).max())
    axes.set_zlim3d(real(modulus).min(), real(modulus).max())
Пример #6
0
def plot_lines(lines):
        for line in lines:
            line_width = 2.0
            x1x2, y1y2, z1z2, color = line
            ax.add_line(art3d.Line3D(x1x2, y1y2, z1z2, lw=line_width, color=color))
            text_args = {'size' : 10, 'zorder' : 1, 'bbox' : box}
            ax.text(x1x2[0], y1y2[0], z1z2[0]+0.5, '0', color='black', **text_args)
Пример #7
0
def threed_plot(df, commod):
    fig = plt.figure()
    ax = plt.axes(projection='3d')

    # Data for a three-dimensional line
    x = [int(i) for i in list(df.index.get_level_values(0).values)]
    y = [int(i) for i in list(df.index.get_level_values(1).values)]
    z = [float(i) for i in list(df[commod].values)]
    for xi, yi, zi in zip(x, y, z):
        line = art3d.Line3D(*zip((xi, yi, min(z)), (xi, yi, zi)),
                            marker='o',
                            markevery=(1, 1))
        ax.add_line(line)
    ax.set_xlim3d(x[0], x[-1])
    ax.set_ylim3d(y[0], y[-1])
    ax.set_zlim3d(min(z), max(z))
    ax.xaxis.set_major_locator(MaxNLocator(integer=True))
    ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    ax.zaxis.set_major_locator(MaxNLocator(5))
    ax.set_title('3D plot of ' + commod)
    ax.set_xlabel(df.index.names[0] + ' [%]')
    ax.set_ylabel(df.index.names[1] + ' [yr]')
    ax.set_zlabel(commod + ' [kg]')
    ax.dist = 11
    fig.savefig(commod, bbox_inches='tight')
    return
Пример #8
0
 def __init__(self, ax):
     self.link = art3d.Line3D(
         [ ],
         [ ],
         [ ],
         color="k",
         linewidth=1
     )
     ax.add_line(self.link)
def draw_boundary(X, Y, Z, ax, N, m, t1, t2, l1, l2, marker, color):

    if t2 < 1:
        ax.view_init(25, 345)
    else:
        ax.view_init(30, 330)

    if N is 1:
        ax.plot_surface(X, Y, Z, linewidth=1, vmin=0, vmax=4)
    else:
        ax.plot_surface(X, Y, Z, linewidth=1, vmin=0, vmax=6)

    coords = [(t1, l1, l2[0]), (t1, l1, l2[1])]
    line_coords = [[(t1, t1), (l1, l1), (0, l2[0])],
                   [(t1, t1), (l1, 4), (l2[0], l2[0])],
                   [(t1, t1), (l1, l1), (l2[0], l2[1])],
                   [(t1, t1), (l1, 4), (l2[1], l2[1])]]

    for idx, (x, y, z) in enumerate(coords):
        ax.scatter3D(x,
                     y,
                     z,
                     marker=marker[idx],
                     s=150,
                     color=color,
                     edgecolor=None)

    for idx, line in enumerate(line_coords):
        ax.add_line(
            art3d.Line3D(line[0], line[1], line[2], color=color, ls="dashed"))

    ax.set_xticks([3, 4, 5, t1])
    ax.set_yticks([1, 2, 3])
    ax.set_zticks([1, 2, 3, 4, 5])

    xticks = ["3", "", "5", ""]
    yticks = ["   $10^{1}$", "", "   $10^{3}$"]
    zticks = ["    $10^{1}$", "", "    $10^{3}$", "", "    $10^{5}$"]

    ax.set_xticklabels(xticks)
    ax.set_yticklabels(yticks)
    ax.set_zticklabels(zticks)

    ax.tick_params(direction='in', pad=-5)

    ax.xaxis.set_rotate_label(False)
    ax.yaxis.set_rotate_label(False)
    ax.zaxis.set_rotate_label(False)

    ax.set_xlabel('$\\tau_1$\n\n', fontsize=10)
    ax.set_ylabel('$L_1$\n\n\n', fontsize=10)  # (agonist)
    ax.set_zlabel('$L_2$      ', fontsize=10)  # (antagonist)

    ax.set_xlim3d(3, t1 - 0.1)
    ax.set_ylim3d(0.1, 3.9)
    ax.set_zlim3d(0.1, 5)
def plot_3d(Q, title=None):
    """
    Draws a 3d plot of a Qnet graph
    Parameters
    :param Q: Qnet Graph
    :param title: Title of Graph
    :return:
    """
    # Create new matplotlib figure and add axes
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    for node in Q.nodes:
        x, y, z = node.coords[0], node.coords[1], node.coords[2]
        # Dictionary between colours and node types
        qnode_color = {
            QNET.Qnode: 'r',
            QNET.Ground: 'y',
            QNET.Swapper: 'c',
            QNET.Satellite: 'b'
        }
        ax.scatter(x, y, z, c=qnode_color[type(node)], marker='o')
        ax.text(x, y, z, '%s' % node.name, size=12, zorder=1)

        # Draw arrow for satellite velocity
        if isinstance(node, QNET.Satellite):
            v = node.velocity
            ax.quiver(x, y, z, v[0], v[1], 0, length=1.5)

    for edge in Q.edges:
        xs = [edge[0].coords[0], edge[1].coords[0]]
        ys = [edge[0].coords[1], edge[1].coords[1]]
        zs = [edge[0].coords[2], edge[1].coords[2]]
        if isinstance(edge[0], QNET.Satellite) or isinstance(
                edge[1], QNET.Satellite):
            line = art3d.Line3D(xs, ys, zs, linestyle='--')
        else:
            line = art3d.Line3D(xs, ys, zs)
        ax.add_line(line)
    if title is not None:
        plt.title(f"{title}")
    fig.show()
Пример #11
0
        def animate(i):
            z = trace_all[:, i]

            for idx, line in enumerate(lines):
                ax.lines[len(edge_list)].remove()

            for idx, line in enumerate(lines):
                line = art3d.Line3D((x[idx], x[idx]), (y[idx], y[idx]),
                                    (0, z[idx]),
                                    marker='D',
                                    markevery=(1, 1),
                                    markerfacecolor='b',
                                    color='b',
                                    alpha=1)
                ax.add_line(line)
            return lines
Пример #12
0
def stem3d(u, v, w, fig=None, markerp="o"):
    r"""This function makes a three dimensional stem plot.
    """
    # Plot to the given axis instance or retrieve the current one
    if fig is None:
        fig = gcf()

    axes = fig.add_subplot(1, 1, 1, projection='3d')

    for ui, vi, wi in zip(u, v, w):
        line = art3d.Line3D(*list(zip((ui, vi, 0), (ui, vi, wi))), marker=markerp, markevery=(1, 1))
        axes.add_line(line)

    axes.set_xlim3d(u.min(), u.max())
    axes.set_ylim3d(v.min(), v.max())
    axes.set_zlim3d(w.min(), w.max())
Пример #13
0
def plot_times_vs_changes_3d(rows):
    fig, ax = base_plot((6, 6, 6), "Parse time vs. change size", "Change size (bytes)", "Change size (chunks)", "Parse time (ms)",
                        {"projection": "3d"})

    x, y, z = zip(*((int(row["Added"]) + int(row["Removed"]), int(row["Changes"]), float(row["Incremental"]))
                    for row in rows if row["Incremental"]))
    # ax.plot(x, y, z, COLORS["Incremental"], label="Incremental", markersize=3)
    for xi, yi, zi in zip(x, y, z):
        ax.add_line(art3d.Line3D(*zip((xi, yi, 0), (xi, yi, zi)), color='g', marker='o', markersize=3, markevery=(1, 1)))

    # We need to manually set the upper limit here, because we don't call a proper plot function but manually draw lines
    ax.set_xlim3d(0, max(1, *x))
    ax.set_ylim3d(0, max(1, *y))
    ax.set_zlim3d(0, max(1, *z))

    ax.view_init(elev=30, azim=-45)
    return fig
Пример #14
0
    def _stem3(self, X, ax=None):
        """
        Draw an image X using 3D stem plot on the given axe object.

        Note that this routine will automatically do a horizontal mirror
        operation given the difference between the image coordinate system and
        the normal Euclidean system. So it does not work for normal stem3
        plotting.

        Parameters
        ----------
        X : numpy.array
            2D matrix to draw.
        ax : matplotlib.axes._subplots.Axes3DSubplot
            The axe object.
        """
        assert len(X.shape) is 2, \
            "Only gray level images are supported. The input's shape is"\
            " {}".format(X.shape)
        # Setup coordinates.
        h, w = X.shape
        x = np.linspace(0, w-1, w)
        y = np.linspace(0, h-1, h)
        xv, yv = np.meshgrid(x, y)

        # If no axis object is given, we need to create it here.
        if ax is None:
            fig = plt.figure()
            ax = fig.add_subplot(1, 1, 1, projection='3d')
        # Draw.
        for row in range(h):
            for x_, y_, z_ in zip(xv[row, :], yv[row, :], X[h-1-row, :]):
                line = art3d.Line3D(*list(zip((x_, y_, 0), (x_, y_, z_))),
                                    marker='o')
                ax.add_line(line)
        ax.set_xlim3d(0, w)
        ax.set_ylim3d(0, h)
        ax.set_zlim3d(min(0, X.min()), X.max() * 1.3)

        plt.show()
Пример #15
0
    def draw_geo_vector_3d(self, vec, ax=None, **kwargs):
        """Draw a :class:`GeoVector3D` into 3D map
        
        :param GeoVector3D vec: the vector 
        
        .. note::
        
            Anchor must be set in the :class:`GeoVector3D` object  
            
        """
        if ax is None:
            ax = self.ax
        try:
            if not isinstance(ax, Axes3D):
                raise ValueError("Need :class:`Axes3D` object as input...")
            elif not vec.type() == "GeoVector3D":
                raise AttributeError("Wrong input, need :class:`GeoVector3D` "
                                     "object")
            elif not vec.anchor.type() == "GeoPoint":
                raise AttributeError("Vector anchor not set or wrong type..")

            if not any([x in kwargs for x in ["ls", "linestyle"]]):
                kwargs["ls"] = "--"

            a = vec.anchor
            pf = a + vec
            x0, y0 = self(a.longitude, a.latitude)
            z0 = a.altitude  #*1000
            x1, y1 = self(pf.longitude, pf.latitude)
            z1 = pf.altitude  #*1000

            l = a3d.Line3D((x0, x1), (y0, y1), (z0, z1), **kwargs)
            handle = ax.add_line(l)
            self.lines[vec.name] = handle
            return pf

        except:
            print(vec.anchor.type())
            raise
Пример #16
0
def Graph3d(x, y, z, **kwargs):
    xmin = kwargs.setdefault('xmin', x.min())
    xmax = kwargs.setdefault('xmax', x.max())
    ymin = kwargs.setdefault('ymin', y.min())
    ymax = kwargs.setdefault('ymax', y.max())
    zmin = kwargs.setdefault('zmin', z.min())
    zmax = kwargs.setdefault('zmax', z.max())

    if 'fig' in kwargs:
        fig = kwargs['fig']
    else:
        fig = plt.figure(figsize=(6,6))
    if 'ax' in kwargs:
        ax = kwargs['ax']
    else:
        ax = fig.add_subplot(1, 1, 1, projection='3d')

    ax._axis3don = False

    for xi, yi, zi in zip(x, y, z):
        if zi >= 0:
            color = 'b'
        else:
            color = 'r'
        line = art3d.Line3D(*zip((xi, yi, 0), (xi, yi, zi)), marker='o',
                            markersize=2, markevery=(1, 1), color=color)
        ax.add_line(line)
    if 'lc' in kwargs:
        ax.add_collection3d(kwargs['lc'])

    ax.set_xlim3d(xmin, xmax)
    ax.set_ylim3d(ymin, ymax)
    ax.set_zlim3d(zmin, zmax)
    ax.set_facecolor('white')
    ax.view_init(elev=30., azim=300)
    plt.tight_layout()
Пример #17
0
def plot_A_3D(
    Xdata,
    Ydata,
    Zdata,
    colormap="RdBu",
    x_min=None,
    x_max=None,
    y_min=None,
    y_max=None,
    z_min=None,
    z_max=None,
    title="",
    xlabel="",
    ylabel="",
    zlabel="",
    xticks=None,
    yticks=None,
    fig=None,
    subplot_index=None,
    is_logscale_x=False,
    is_logscale_y=False,
    is_logscale_z=False,
    is_disp_title=True,
    type="stem",
    save_path=None,
):
    """Plots a 3D graph ("stem", "surf" or "pcolor")

    Parameters
    ----------
    Xdata : ndarray
        array of x-axis values
    Ydata : ndarray
        array of y-axis values
    Zdata : ndarray
        array of z-axis values
    colormap : colormap object
        colormap prescribed by user
    x_min : float
        minimum value for the x-axis (no automated scaling in 3D)
    x_max : float
        maximum value for the x-axis (no automated scaling in 3D)
    y_min : float
        minimum value for the y-axis (no automated scaling in 3D)
    y_max : float
        maximum value for the y-axis (no automated scaling in 3D)
    z_min : float
        minimum value for the z-axis (no automated scaling in 3D)
    z_max : float
        maximum value for the z-axis (no automated scaling in 3D)
    title : str
        title of the graph
    xlabel : str
        label for the x-axis
    ylabel : str
        label for the y-axis
    zlabel : str
        label for the z-axis
    xticks : list
        list of ticks to use for the x-axis
    fig : Matplotlib.figure.Figure
        existing figure to use if None create a new one
    subplot_index : int
        index of subplot in which to plot
    is_logscale_x : bool
        boolean indicating if the x-axis must be set in logarithmic scale
    is_logscale_y : bool
        boolean indicating if the y-axis must be set in logarithmic scale
    is_logscale_z : bool
        boolean indicating if the z-axis must be set in logarithmic scale
    is_disp_title : bool
        boolean indicating if the title must be displayed
    type : str
        type of 3D graph : "stem", "surf", "pcolor" or "scatter"
    """

    # Set figure/subplot
    is_show_fig = True if fig is None else False
    is_3d = False
    if type != "pcolor" and type != "scatter":
        is_3d = True
    fig, ax = init_subplot(fig=fig, subplot_index=subplot_index, is_3d=is_3d)

    # Plot
    if type == "stem":
        for xi, yi, zi in zip(Xdata, Ydata, Zdata):
            line = art3d.Line3D(*zip((xi, yi, 0), (xi, yi, zi)),
                                linewidth=3.0,
                                marker="o",
                                markersize=5.0,
                                markevery=(1, 1),
                                color=COLORS[0])
            ax.add_line(line)
        ax.set_xlim3d(x_max, x_min)
        ax.set_ylim3d(y_min, y_max)
        ax.set_zlim3d(z_min, z_max)
        # set correct angle
        ax.view_init(elev=20.0, azim=45)
        ax.zaxis.set_rotate_label(False)
        ax.set_zlabel(zlabel, rotation=0)
        ax.xaxis.labelpad = 30
        ax.yaxis.labelpad = 30
        ax.zaxis.labelpad = 30
        if xticks is not None:
            ax.xaxis.set_ticks(xticks)
        if yticks is not None:
            ax.yaxis.set_ticks(yticks)
        # white background
        ax.xaxis.pane.fill = False
        ax.yaxis.pane.fill = False
        ax.zaxis.pane.fill = False
        ax.xaxis.pane.set_edgecolor("w")
        ax.yaxis.pane.set_edgecolor("w")
        ax.zaxis.pane.set_edgecolor("w")
        if is_logscale_z:
            ax.zscale("log")
    elif type == "surf":
        ax.plot_surface(Xdata, Ydata, Zdata, cmap=colormap)
        ax.set_xlim3d(x_max, x_min)
        ax.set_ylim3d(y_min, y_max)
        ax.set_zlim3d(z_min, z_max)
        ax.zaxis.set_rotate_label(False)
        ax.set_zlabel(zlabel, rotation=0)
        ax.xaxis.labelpad = 30
        ax.yaxis.labelpad = 30
        ax.zaxis.labelpad = 30
        if xticks is not None:
            ax.xaxis.set_ticks(xticks)
        if yticks is not None:
            ax.yaxis.set_ticks(yticks)
        # white background
        ax.xaxis.pane.fill = False
        ax.yaxis.pane.fill = False
        ax.zaxis.pane.fill = False
        ax.xaxis.pane.set_edgecolor("w")
        ax.yaxis.pane.set_edgecolor("w")
        ax.zaxis.pane.set_edgecolor("w")
        if is_logscale_z:
            ax.zscale("log")
    elif type == "pcolor":
        c = ax.pcolormesh(Xdata,
                          Ydata,
                          Zdata,
                          cmap=colormap,
                          vmin=z_min,
                          vmax=z_max)
        clb = fig.colorbar(c, ax=ax)
        clb.ax.set_title(zlabel, fontsize=18, fontname=FONT_NAME)
        clb.ax.tick_params(labelsize=18)
        for l in clb.ax.yaxis.get_ticklabels():
            l.set_family(FONT_NAME)
        if xticks is not None:
            ax.xaxis.set_ticks(xticks)
        if yticks is not None:
            ax.yaxis.set_ticks(yticks)
    elif type == "scatter":
        c = ax.scatter(Xdata,
                       Ydata,
                       c=Zdata,
                       marker="s",
                       cmap=colormap,
                       vmin=z_min,
                       vmax=z_max)
        clb = fig.colorbar(c, ax=ax)
        clb.ax.set_title(zlabel, fontsize=18, fontname=FONT_NAME)
        clb.ax.tick_params(labelsize=18)
        for l in clb.ax.yaxis.get_ticklabels():
            l.set_family(FONT_NAME)
        if xticks is not None:
            ax.xaxis.set_ticks(xticks)
        if yticks is not None:
            ax.yaxis.set_ticks(yticks)

    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    if is_logscale_x:
        ax.xscale("log")

    if is_logscale_y:
        ax.yscale("log")

    if is_disp_title:
        ax.set_title(title)

    if is_3d:
        for item in ([ax.xaxis.label, ax.yaxis.label, ax.zaxis.label] +
                     ax.get_xticklabels() + ax.get_yticklabels() +
                     ax.get_zticklabels()):
            item.set_fontsize(22)
    else:
        for item in ([ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() +
                     ax.get_yticklabels()):
            item.set_fontsize(22)
            item.set_fontname(FONT_NAME)
    ax.title.set_fontsize(24)
    ax.title.set_fontname(FONT_NAME)

    if save_path is not None:
        fig.savefig(save_path)
        plt.close()

    if is_show_fig:
        fig.show()
Пример #18
0
                plt.draw()
                plt.pause(.01)

fig = plt.figure()
fig.set_size_inches(15, 15)

ax = fig.add_subplot(111, projection='3d', aspect='equal')
ax.view_init(azim=17,elev = 17)
ax.grid(False)

ax.set_xlim(16, 0)
ax.set_ylim(0, 16)
ax.set_zlim(0, 16)

ax.set_xticklabels('')
ax.set_ylabel('Time')
ax.set_yticklabels(list(range(0,9)))
ax.set_zticklabels(['', 'P_3', '', '', 'P_2', '', '', 'P_1'])

ax.set_title('Lamport\'s Clocks (Multicast System)', fontsize=16)

for line in lines:
    x1x2, y1y2, z1z2, line_width, color = line
    ax.add_line(art3d.Line3D(x1x2, y1y2, z1z2, lw=line_width, color=color))
    ax.text(x1x2[0], y1y2[0], z1z2[0]+0.5, 0, size=10, zorder=1,
            color='black', bbox={'alpha': 0.1, 'pad': 1})

for arrow in points1:
    plot_process(arrow)
plt.show()
# rotation_view(ax,plt)
Пример #19
0
nentries=x_chmap.shape[0]
ncolors=x_chmap[0].shape[3]

xcenter=x_chmap[0].shape[0]/2
xmax=x_chmap[0].shape[0]
ycenter=x_chmap[0].shape[1]/2
ymax=x_chmap[0].shape[1]
zcenter=x_chmap[0].shape[2]/2

print(ncolors)

for i in range(nentries):
    print(x_chmap[i].shape)
    for j in [0]: #range(ncolors):
        ax,plot,x,y,z,c=plot4d(x_chmap[i][:,:,:,j:j+1],'','etabin','layer','phibin')
        
        l = a3d.Line3D((xcenter,xcenter),(0,0),(0,ymax),c = 'k', ls = '--')
        ax.add_line(l)
        l2 = a3d.Line3D((0,xmax),(0,0),(ycenter,ycenter),c = 'k', ls = '--')
        ax.add_line(l2)
        #ax.view_init(0,90)
        
        #ax.plot(x, y, 'r+', zdir='y')#, zs=1.5)
        #ax.plot(z, y, 'g+', zdir='x')#, zs=-0.5)
        #ax.plot(x, z, 'b+', zdir='z')#, zs=-1.5)

        plot.show()
        #input("Press [enter] to continue.")
        plot.close()
    
Пример #20
0
                detection_xs.append(repeat)
            else:
                detection_xs.append(ext_offset)
            detection_ys.append(width)
            detection_zs.append(offset)

        results_table.append(
            [f, total_samples, successes_total,
             len(results['detections'])])
    else:
        results_table.append([f, total_samples, successes_total, 0])

    for idx in range(len(xs)):
        l = a3d.Line3D((xs[idx], xs[idx]), (ys[idx], ys[idx]),
                       (min(results['parameters']['offsets']) - 2, zs[idx]),
                       color='gray',
                       ls='--',
                       linewidth=.5)
        l.set_alpha(0.5)
        ax.add_line(l)
    for idx in range(len(detection_xs)):
        l = a3d.Line3D(
            (detection_xs[idx], detection_xs[idx]),
            (detection_ys[idx], detection_ys[idx]),
            (min(results['parameters']['offsets']) - 2, detection_zs[idx]),
            color='red',
            ls='--',
            linewidth=.5)
        l.set_alpha(0.5)
        ax.add_line(l)
Пример #21
0
def axes3d(fig, reflevel,  xr, yr, zr, xsize, ysize, zsize):
    # get 3d axes
    ax = fig.gca(projection='3d')



    # create 3d coordinate axes lines which cuts the point at xr, yr and zr
    line=art3d.Line3D(*zip((0, yr, zr), (xsize*2**reflevel, yr, zr)),
                      color='black', linewidth=0.8, alpha=0.25, zorder=100)
    ax.add_line(line)
    line=art3d.Line3D(*zip((xr, 0, zr), (xr, ysize*2**reflevel, zr)),
                      color='black', linewidth=0.8, alpha=0.25, zorder=100)
    ax.add_line(line)
    line=art3d.Line3D(*zip((xr, yr, 0), (xr, yr, ysize*2**reflevel)),
                      color='black', linewidth=0.8, alpha=0.25, zorder=100)
    ax.add_line(line)



    # spacing between ticks
    s = int((xsize*2**reflevel)/20)
    # widths of the ticks
    l = int((xsize*2**reflevel)/100)


    ###################
    # plot ticks STARTS    

    # plot the first ticks which position > xr or in the others yr or zr
    i = 1
    while xr+i*s < xsize*2**reflevel:
      line=art3d.Line3D(*zip((xr+i*s, yr-l, zr), (xr+i*s, yr+l, zr)),
                        color='black', linewidth=0.7, alpha=0.25, zorder=100+i)
      ax.add_line(line)
      line=art3d.Line3D(*zip((xr+i*s, yr, zr-l), (xr+i*s, yr, zr+l)),
                        color='black', linewidth=0.7, alpha=0.25, zorder=100+i)
      ax.add_line(line)
      i += 1

    # plot the last ticks which position < xr or in the others yr or zr
    i = 1
    while xr-i*s > 0:
      line=art3d.Line3D(*zip((xr-i*s, yr-l, zr), (xr-i*s, yr+l, zr)),
                        color='black', linewidth=0.7, alpha=0.25, zorder=100+i)
      ax.add_line(line)
      line=art3d.Line3D(*zip((xr-i*s, yr, zr-l), (xr-i*s, yr, zr+l)),
                        color='black', linewidth=0.7, alpha=0.25, zorder=100+i)
      ax.add_line(line)
      i += 1


    i = 1
    while yr+i*s < ysize*2**reflevel:
      line=art3d.Line3D(*zip((xr-l, yr+i*s, zr), (xr+l, yr+i*s, zr)),
                        color='black', linewidth=0.7, alpha=0.25, zorder=100+i)
      ax.add_line(line)
      line=art3d.Line3D(*zip((xr, yr+i*s, zr-l), (xr, yr+i*s, zr+l)),
                        color='black', linewidth=0.7, alpha=0.25, zorder=100+i)
      ax.add_line(line)
      i += 1

    i = 1
    while yr-i*s > 0:
      line=art3d.Line3D(*zip((xr-l, yr-i*s, zr), (xr+l, yr-i*s, zr)),
                        color='black', linewidth=0.7, alpha=0.25, zorder=100+i)
      ax.add_line(line)
      line=art3d.Line3D(*zip((xr, yr-i*s, zr-l), (xr, yr-i*s, zr+l)),
                        color='black', linewidth=0.7, alpha=0.25, zorder=100+i)
      ax.add_line(line)
      i += 1


    i = 1
    while zr+i*s < zsize*2**reflevel:
      line=art3d.Line3D(*zip((xr, yr-l, zr+i*s), (xr, yr+l, zr+i*s)),
                        color='black', linewidth=0.7, alpha=0.25, zorder=100+i)
      ax.add_line(line)
      line=art3d.Line3D(*zip((xr-l, yr, zr+i*s), (xr+l, yr, zr+i*s)),
                        color='black', linewidth=0.7, alpha=0.25, zorder=100+i)
      ax.add_line(line)
      i += 1

    i = 1
    while zr-i*s > 0:
      line=art3d.Line3D(*zip((xr, yr-l, zr-i*s), (xr, yr+l, zr-i*s)),
                        color='black', linewidth=0.7, alpha=0.25, zorder=100+i)
      ax.add_line(line)
      line=art3d.Line3D(*zip((xr-l, yr, zr-i*s), (xr+l, yr, zr-i*s)),
                        color='black', linewidth=0.7, alpha=0.25, zorder=100+i)
      ax.add_line(line)
      i += 1

    # plot ticks ENDS
    #################



    # set the basic 3d coordinate axes off
    ax.set_axis_off()

    # return axes
    return ax
def plot_decays(decay_positions, four_vecs_lab_particle1, four_vecs_lab_particle2, z_detector, r=5):
    fig = plt.figure()
    ax = fig.gca(projection='3d')

    decay_plot_count = 0

    for decay_pos, fv1, fv2 in zip(decay_positions, four_vecs_lab_particle1, four_vecs_lab_particle2):

            x, y, z = decay_pos
            if z > z_detector:
                continue

            decay_plot_count += 1
            if decay_plot_count > max_decays_to_plot:
                break

            p1 = fv1[1:]
            p2 = fv2[1:]
            direction1 = p1/np.linalg.norm(p1)
            direction2 = p2/np.linalg.norm(p2)

            scale_factor1 = (z_detector - z)/direction1[2]
            scale_factor2 = (z_detector - z)/direction2[2]

            dx1, dy1, dz1 = direction1 * abs(scale_factor1)
            dx2, dy2, dz2 = direction2 * abs(scale_factor2)

            if double_hit(decay_pos, fv1, fv2, z_detector, r):
                ax.plot([z, z+dz1], [y, y+dy1], [x, x+dx1], color="green")
                ax.plot([z, z+dz2], [y, y+dy2], [x, x+dx2], color="green")
                continue

            if single_hit(decay_pos, fv1, z_detector, r):
                ax.plot([z, z+dz1], [y, y+dy1], [x, x+dx1], color="orange")
                ax.plot([z, z+dz2], [y, y+dy2], [x, x+dx2], color="orange")
                continue

            if single_hit(decay_pos, fv2, z_detector, r):
                ax.plot([z, z+dz1], [y, y+dy1], [x, x+dx1], color="orange")
                ax.plot([z, z+dz2], [y, y + dy2], [x, x+dx2], color="orange")
                continue

            ax.plot([z, z + dz1], [y, y + dy1], [x, x + dx1], color="red")
            ax.plot([z, z + dz2], [y, y + dy2], [x, x + dx2], color="red")



    ax.plot([0, z_detector], [0, 0], [0, 0])
    ax.scatter([0], [0], [0], s=60, label='origin')

    #Mald Zentrum des Detektors
    ax.scatter([z_detector], [0], [0], "y",s=60, label='detector', color="red")

    #Malt den Detektorumfang, check nicht wie man die Achsen richtig skaliert
    edge_steps = 300
    edge = np.zeros((edge_steps, 3))
    for counter in range(edge_steps):
        angle = 2*np.pi*counter/edge_steps
        edge[counter] = [z_detector, r*np.sin(angle), r*np.cos(angle)]
    ax.scatter(edge[:,0], edge[:,1], edge[:,2], s=20, color="red")

    #setzt die Axen fest
    ax.set_ylim3d(-2.5, 2.5)
    ax.set_zlim3d(-2.5, 2.5)

    #zeichnet eine schoene legende
    green_line = art3d.Line3D(0, 0, 0, color="green")
    red_line = art3d.Line3D(0, 0, 0, color="red")
    orange_line = art3d.Line3D(0, 0, 0, color="orange")
    ax.legend([green_line, red_line, orange_line],
              ["hit, both particles", "miss, both particles", "1 hit, 1 missed"])
    plt.show()
Пример #23
0
def plot_3D(
    Xdata,
    Ydata,
    Zdata,
    colormap="RdBu_r",
    color_list=None,
    x_min=None,
    x_max=None,
    y_min=None,
    y_max=None,
    z_min=None,
    z_max=None,
    title="",
    xlabel="",
    ylabel="",
    zlabel="",
    xticks=None,
    yticks=None,
    fig=None,
    ax=None,
    is_logscale_x=False,
    is_logscale_y=False,
    is_logscale_z=False,
    is_disp_title=True,
    type_plot="stem",
    is_contour=False,
    save_path=None,
    is_show_fig=None,
    is_switch_axes=False,
    win_title=None,
    font_name="arial",
    font_size_title=12,
    font_size_label=10,
    font_size_legend=8,
):
    """Plots a 3D graph ("stem", "surf" or "pcolor")

    Parameters
    ----------
    Xdata : ndarray
        array of x-axis values
    Ydata : ndarray
        array of y-axis values
    Zdata : ndarray
        array of z-axis values
    colormap : colormap object
        colormap prescribed by user
    x_min : float
        minimum value for the x-axis (no automated scaling in 3D)
    x_max : float
        maximum value for the x-axis (no automated scaling in 3D)
    y_min : float
        minimum value for the y-axis (no automated scaling in 3D)
    y_max : float
        maximum value for the y-axis (no automated scaling in 3D)
    z_min : float
        minimum value for the z-axis (no automated scaling in 3D)
    z_max : float
        maximum value for the z-axis (no automated scaling in 3D)
    title : str
        title of the graph
    xlabel : str
        label for the x-axis
    ylabel : str
        label for the y-axis
    zlabel : str
        label for the z-axis
    xticks : list
        list of ticks to use for the x-axis
    fig : Matplotlib.figure.Figure
        existing figure to use if None create a new one
    ax : Matplotlib.axes.Axes object
        ax on which to plot the data
    is_logscale_x : bool
        boolean indicating if the x-axis must be set in logarithmic scale
    is_logscale_y : bool
        boolean indicating if the y-axis must be set in logarithmic scale
    is_logscale_z : bool
        boolean indicating if the z-axis must be set in logarithmic scale
    is_disp_title : bool
        boolean indicating if the title must be displayed
    type_plot : str
        type of 3D graph : "stem", "surf", "pcolor" or "scatter"
    is_contour : bool
        True to show contour line if type_plot = "pcolor"
    save_path : str
        full path including folder, name and extension of the file to save if save_path is not None
    is_show_fig : bool
        True to show figure after plot
    is_switch_axes : bool
        to switch x and y axes
    """

    # Set if figure must be shown if is_show_fig is None
    if is_show_fig is None:
        is_show_fig = True if fig is None else False

    # Set if figure is 3D
    if type_plot not in ["pcolor", "pcolormesh", "scatter"]:
        is_3d = True
    else:
        is_3d = False

    # Set figure if needed
    if fig is None and ax is None:
        (fig, ax, _, _) = init_fig(fig=None, shape="rectangle", is_3d=is_3d)

    if color_list is None:
        color_list = COLORS

    # Calculate z limits
    if z_min is None:
        z_min = np_min(Zdata)
    if z_max is None:
        z_max = np_max(Zdata)

    # Check logscale on z axis
    if is_logscale_z:
        Zdata = 10 * log10(np_abs(Zdata))
        clb_format = "%0.0f"
    else:
        clb_format = "%.4g"

    # Switch axes
    if is_switch_axes:
        Xdata, Ydata = Ydata, Xdata
        if len(Xdata.shape) > 1:
            Xdata = Xdata.T
        if len(Ydata.shape) > 1:
            Ydata = Ydata.T
        if len(Zdata.shape) > 1:
            Zdata = Zdata.T
        x_min, y_min = y_min, x_min
        x_max, y_max = y_max, x_max
        xlabel, ylabel = ylabel, xlabel
        xticks, yticks = yticks, xticks
        is_logscale_x, is_logscale_y = is_logscale_y, is_logscale_x

    # Plot
    if type_plot == "stem":
        cmap = matplotlib.cm.get_cmap(colormap)
        for xi, yi, zi in zip(Xdata, Ydata, Zdata):
            line = art3d.Line3D(*zip((xi, yi, 0), (xi, yi, zi)),
                                linewidth=2.0,
                                marker="o",
                                markersize=3.0,
                                markevery=(1, 1),
                                color=cmap(0))
            ax.add_line(line)
        ax.set_xlim3d(x_max, x_min)
        ax.set_ylim3d(y_min, y_max)
        ax.set_zlim3d(z_min, z_max)
        # set correct angle
        ax.view_init(elev=20.0, azim=45)
        ax.zaxis.set_rotate_label(False)
        ax.set_zlabel(zlabel, rotation=0)
        ax.xaxis.labelpad = 5
        ax.yaxis.labelpad = 5
        ax.zaxis.labelpad = 5
        if xticks is not None:
            ax.xaxis.set_ticks(xticks)
        if yticks is not None:
            ax.yaxis.set_ticks(yticks)
        # white background
        ax.xaxis.pane.fill = False
        ax.yaxis.pane.fill = False
        ax.zaxis.pane.fill = False
        ax.xaxis.pane.set_edgecolor("w")
        ax.yaxis.pane.set_edgecolor("w")
        ax.zaxis.pane.set_edgecolor("w")
        if is_logscale_z:
            ax.zscale("log")
    elif type_plot == "surf":
        ax.plot_surface(Xdata, Ydata, Zdata, cmap=colormap)
        ax.set_xlim3d(x_max, x_min)
        ax.set_ylim3d(y_min, y_max)
        ax.set_zlim3d(z_min, z_max)
        ax.zaxis.set_rotate_label(False)
        ax.set_zlabel(zlabel, rotation=0)
        ax.xaxis.labelpad = 5
        ax.yaxis.labelpad = 5
        ax.zaxis.labelpad = 5
        if xticks is not None:
            ax.xaxis.set_ticks(xticks)
        if yticks is not None:
            ax.yaxis.set_ticks(yticks)
        # white background
        ax.xaxis.pane.fill = False
        ax.yaxis.pane.fill = False
        ax.zaxis.pane.fill = False
        ax.xaxis.pane.set_edgecolor("w")
        ax.yaxis.pane.set_edgecolor("w")
        ax.zaxis.pane.set_edgecolor("w")
        if is_logscale_z:
            ax.zscale("log")
    elif type_plot == "pcolor":
        Zdata[Zdata < z_min] = z_min
        Zdata[Zdata > z_max] = z_max
        # Handle descending order axes (e.g. spectrogram of run-down in freq/rpm map)
        if Ydata[-1] < Ydata[0]:
            Ydata = Ydata[::-1]
            Zdata = Zdata[:, ::-1]
        if Xdata[-1] < Xdata[0]:
            Xdata = Xdata[::-1]
            Zdata = Zdata[::-1, :]
        im = NonUniformImage(
            ax,
            interpolation="bilinear",
            extent=(x_min, x_max, y_max, y_min),
            cmap=colormap,
            picker=10,
        )
        im.set_data(Xdata, Ydata, Zdata.T)
        im.set_clim(z_min, z_max)
        ax.images.append(im)
        if is_contour:
            ax.contour(Xdata, Ydata, Zdata.T, colors="black", linewidths=0.8)
        clb = fig.colorbar(im, ax=ax, format=clb_format)
        clb.ax.set_title(zlabel, fontsize=font_size_legend, fontname=font_name)
        clb.ax.tick_params(labelsize=font_size_legend)
        for l in clb.ax.yaxis.get_ticklabels():
            l.set_family(font_name)
        if xticks is not None:
            ax.xaxis.set_ticks(xticks)
        if yticks is not None:
            ax.yaxis.set_ticks(yticks)
        ax.set_xlim([x_min, x_max])
        ax.set_ylim([y_min, y_max])
    elif type_plot == "pcolormesh":
        c = ax.pcolormesh(Xdata,
                          Ydata,
                          Zdata,
                          cmap=colormap,
                          shading="gouraud",
                          antialiased=True)
        clb = fig.colorbar(c, ax=ax)
        clb.ax.set_title(zlabel, fontsize=font_size_legend, fontname=font_name)
        clb.ax.tick_params(labelsize=font_size_legend)
        for l in clb.ax.yaxis.get_ticklabels():
            l.set_family(font_name)
        if xticks is not None:
            ax.xaxis.set_ticks(xticks)
        if yticks is not None:
            ax.yaxis.set_ticks(yticks)
        ax.set_xlim([x_min, x_max])
        ax.set_ylim([y_min, y_max])
    elif type_plot == "scatter":
        c = ax.scatter(
            Xdata,
            Ydata,
            # s=10,
            c=Zdata,
            marker=".",
            cmap=colormap,
            vmin=z_min,
            vmax=z_max,
            picker=True,
            pickradius=5,
        )
        clb = fig.colorbar(c, ax=ax)
        clb.ax.set_title(zlabel, fontsize=font_size_legend, fontname=font_name)
        clb.ax.tick_params(labelsize=font_size_legend)
        for l in clb.ax.yaxis.get_ticklabels():
            l.set_family(font_name)
        if xticks is not None:
            ax.xaxis.set_ticks(xticks)
        if yticks is not None:
            ax.yaxis.set_ticks(yticks)

    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    if is_logscale_x:
        ax.xscale("log")

    if is_logscale_y:
        ax.yscale("log")

    if is_disp_title:
        ax.set_title(title)

    if is_3d:
        for item in ([ax.xaxis.label, ax.yaxis.label, ax.zaxis.label] +
                     ax.get_xticklabels() + ax.get_yticklabels() +
                     ax.get_zticklabels()):
            item.set_fontsize(font_size_label)
    else:
        for item in ([ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() +
                     ax.get_yticklabels()):
            item.set_fontsize(font_size_label)
            item.set_fontname(font_name)
    ax.title.set_fontsize(font_size_title)
    ax.title.set_fontname(font_name)

    if save_path is not None:
        save_path = save_path.replace("\\", "/")
        fig.savefig(save_path)
        plt.close()

    if is_show_fig:
        fig.show()

    if win_title:
        manager = plt.get_current_fig_manager()
        if manager is not None:
            manager.set_window_title(win_title)
Пример #24
0
 def _draw_line3D(self, X, Y, Z, *args, **kwargs):
     artist = art3d.Line3D(X, Y, Z, *args, **kwargs)
     self.main_ax.add_line(artist)
     return artist
color2 = [0, 0, 255]

ax.plot([color1[0]], [color1[1]], [color1[2]],
        color='r',
        label='color1',
        marker='o',
        markersize=20)
ax.plot([color2[0]], [color2[1]], [color2[2]],
        color='b',
        label='color2',
        marker='o',
        markersize=20)
ax.legend()

# Draw a line
import mpl_toolkits.mplot3d.art3d as art3d
line = art3d.Line3D([2, 3, 4, 5, 6, 7, 8], [2, 3, 4, 5, 6, 7, 8],
                    [3, 5, 3, 5, 3, 5, 3],
                    color='g')
ax.add_line(line)

ax.set_title("Color distance", fontsize=16)
ax.set_xlabel(r'$R$', fontsize=20, color='r')
ax.set_ylabel(r'$G$', fontsize=20, color='g')
ax.set_zlabel(r'$B$', fontsize=20, color='b')

ax.set_xticklabels([0, 50, 100, 150, 200, 250], fontsize=10)
ax.set_yticklabels([0, 50, 100, 150, 200, 250], fontsize=10)
ax.set_zticklabels([0, 50, 100, 150, 200, 250], fontsize=10)

plt.show()
#     v_y = []
#     v_z = []
#     for z in flr:
#         for v in z:
#             v_x.append(v[1])
#             v_y.append(v[2])
#             v_z.append(v[3])
#             line = art3d.Line3D(v_x, v_y, v_z, color='gray')
#             ax.add_line(line)

# Plot all connections
for c in c_set:
    x_edge = [c[0][1], c[1][1]]
    y_edge = [c[0][2], c[1][2]]
    z_edge = [c[0][3], c[1][3]]
    line = art3d.Line3D(x_edge, y_edge, z_edge, color='black')
    ax.add_line(line)

# Make arrays for the edges of the path to plot
e_x = []
e_y = []
e_z = []
for i in path:
    e_x.append(v_set[i][1])
    e_y.append(v_set[i][2])
    e_z.append(v_set[i][3])
    line = art3d.Line3D(e_x, e_y, e_z, color='red')
    ax.add_line(line)

plt.show()
Пример #27
0
    def plot_node_3d(self,
                     pos_coordinates,
                     edge_list,
                     node_values,
                     view_angle,
                     nodeIdx,
                     figIdx=0,
                     save_fig=False):
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1, projection='3d')
        [elev, azim] = view_angle
        ax.view_init(elev, azim)

        x = pos_coordinates[:, 0]
        y = pos_coordinates[:, 1]
        z = node_values
        # plot a zero-plane
        Sx = np.linspace(min(x), max(x), 100)
        Sy = np.linspace(min(y), max(y), 100)
        SurfaceX, SurfaceY = np.meshgrid(Sx, Sy)
        SurfaceZ = np.zeros((len(Sx), ))
        ax.plot_surface(SurfaceX,
                        SurfaceY,
                        SurfaceZ,
                        rstride=8,
                        cstride=8,
                        alpha=0.05)

        for edge in edge_list:
            n0_idx = next(
                (item['loc'] for item in nodeIdx if item['node'] == edge[0]))
            n1_idx = next(
                (item['loc'] for item in nodeIdx if item['node'] == edge[1]))
            lx = np.array((x[n0_idx], x[n1_idx]))
            ly = np.array((y[n0_idx], y[n1_idx]))
            line = art3d.Line3D(lx,
                                ly,
                                np.zeros((2, )),
                                marker='o',
                                markevery=(0, 1),
                                markerfacecolor='r',
                                color='k',
                                linewidth=0.5)
            ax.add_line(line)
        # plot node and node-attributes in stem plot
        for xi, yi, zi in zip(x, y, z):
            line = art3d.Line3D(*zip((xi, yi, 0), (xi, yi, zi)),
                                marker='D',
                                markevery=(1, 1),
                                markerfacecolor='b',
                                color='b',
                                alpha=1)
            ax.add_line(line)

        ax.set_xlim3d(min(x), max(x))
        ax.set_ylim3d(min(y), max(y))
        ax.set_zlim3d(min([min(z), -1]), max([max(z), 1]))
        plt.show()
        #filename = "../figures/" +  strftime("%d%m%Y_%H%M%S", gmtime()) + "_netNode"+ str(figIdx) +".eps"
        #fig.savefig(filename, format='eps', dpi=1000)
        if save_fig == True:
            filename = "../figures/" + strftime(
                "%d%m%Y_%H%M%S", gmtime()) + "_netNode" + str(figIdx) + ".png"
            fig.savefig(filename)
Пример #28
0
    def make_animate(self, G, view_angle, save_anime=False):
        pos_coordinates, edge_list, trace_all, nodeIdx = self.draw_data_prepare(
            G)

        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1, projection='3d')
        [elev, azim] = view_angle
        ax.view_init(elev, azim)

        x = pos_coordinates[:, 0]
        y = pos_coordinates[:, 1]
        z = trace_all[:, 0]
        # plot a zero-plane
        Sx = np.linspace(min(x), max(x), 100)
        Sy = np.linspace(min(y), max(y), 100)
        SurfaceX, SurfaceY = np.meshgrid(Sx, Sy)
        SurfaceZ = np.zeros((len(Sx), ))
        ax.plot_surface(SurfaceX,
                        SurfaceY,
                        SurfaceZ,
                        rstride=8,
                        cstride=8,
                        alpha=0.05)
        for edge in edge_list:
            n0_idx = next(
                (item['loc'] for item in nodeIdx if item['node'] == edge[0]))
            n1_idx = next(
                (item['loc'] for item in nodeIdx if item['node'] == edge[1]))
            lx = np.array((x[n0_idx], x[n1_idx]))
            ly = np.array((y[n0_idx], y[n1_idx]))
            #line=ax.quiver(x[n0_idx], y[n0_idx], 0, (x[n1_idx]- x[n0_idx]), (y[n1_idx]- y[n0_idx]), 0 , marker='o', markevery=(0, 1), markerfacecolor='r', color='k', linewidth=0.5)
            line = art3d.Line3D(lx,
                                ly,
                                np.zeros((2, )),
                                marker='o',
                                markevery=(0, 1),
                                markerfacecolor='r',
                                color='k',
                                linewidth=0.5)
            ax.add_line(line)
        # plot node and node-attributes in stem plot
        lines = []  #record line objects
        for xi, yi, zi in zip(x, y, z):
            line = art3d.Line3D(*zip((xi, yi, 0), (xi, yi, zi)),
                                marker='D',
                                markevery=(1, 1),
                                markerfacecolor='b',
                                color='b',
                                alpha=1)
            ax.add_line(line)
            lines.append(line)

        ax.set_xlim3d(min(x), max(x))
        ax.set_ylim3d(min(y), max(y))
        ax.set_zlim3d(min([min(z), -1]), max([max(z), 1]))

        def animate(i):
            z = trace_all[:, i]

            for idx, line in enumerate(lines):
                ax.lines[len(edge_list)].remove()

            for idx, line in enumerate(lines):
                line = art3d.Line3D((x[idx], x[idx]), (y[idx], y[idx]),
                                    (0, z[idx]),
                                    marker='D',
                                    markevery=(1, 1),
                                    markerfacecolor='b',
                                    color='b',
                                    alpha=1)
                ax.add_line(line)
            return lines

        def init():
            for line in lines:
                line.set_data([], [])
            return lines

        # call the animator.  blit=True means only re-draw the parts that have changed.
        anim = animation.FuncAnimation(fig,
                                       animate,
                                       init_func=init,
                                       frames=trace_all.shape[1],
                                       interval=30,
                                       blit=True)
        if save_anime == True:
            filename = "../figures/" + strftime(
                "%d%m%Y_%H%M%S", gmtime()) + "_netAnime" + ".mp4"
            anim.save(filename, fps=10, extra_args=['-vcodec', 'libx264'])
Пример #29
0
    def scatter3d(self,
                  x,
                  y,
                  z,
                  filename=None,
                  spot_cols=None,
                  label=False,
                  stem=True,
                  label_font_size=6,
                  rotation=134,
                  elevation=48,
                  squish_scales=False,
                  spot_size=40,
                  depthshade=True,
                  **kargs):
        """
        **Purpose**
            plot a scatter plot of PCx against PCy against PCz
            This is the 3D variant

        **Arguments**
            x, y, z (Required)
                PC dimension to plot as scatter
                Note that PC begin at 1 (and not at zero, as might be expected)

            spot_cols (Optional, default="black" or self.set_cols())
                list of colours for the samples, should be the same length as
                the number of conditions.

            spot_size (Optional, default=40)
                The relative spot size.

            label (Optional, default=False)
                label each spot with the name of the condition

            label_font_size (Optional, default=6)
                label font size.

            stem (Optional, default=False)
                Draw stems from the spot down to the base of the graph. (i.e. z=0)

            rotation (Optional, default=134)
                The rotation along the X, Y plane

            elevation (Optional, default=48
                The rotation along the Z plane.

            depthshade (Optional, default=True)
                turn on or off matplotlib depth shading of the points in the 3D acise

        **Returns**
            None
        """
        assert filename, "scatter: Must provide a filename"

        xdata = self.__transform[:, x - 1]
        ydata = self.__transform[:, y - 1]
        zdata = self.__transform[:, z - 1]
        perc_weights = self.get_loading_percents()

        fig = self.__draw.getfigure(**kargs)
        ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=elevation, azim=rotation)

        cols = self.cols
        if spot_cols:
            cols = spot_cols

        sc = ax.scatter(
            xdata,
            ydata,
            zdata,
            #edgecolors="none",
            c=cols,
            s=spot_size,
            depthshade=depthshade)

        sc.set_edgecolor('none')

        if label:
            for i, lab in enumerate(self.labels):
                ax.text(xdata[i],
                        ydata[i],
                        zdata[i],
                        lab,
                        size=label_font_size,
                        ha="center",
                        va="bottom")

        if stem:  # stem must go after scatter for sorting. Actually, not true right? matplotlib uses zorder for that...
            z_min = min(zdata)
            for x_, y_, z_ in zip(xdata, ydata, zdata):
                line = art3d.Line3D(*list(zip((x_, y_, z_min), (x_, y_, z_))),
                                    marker=None,
                                    c="grey",
                                    alpha=0.1)
                ax.add_line(line)

        ax.set_xlabel(
            "PC%s (%.1f%%)" %
            (x, perc_weights[x - 1]))  # can be overridden via do_common_args()
        ax.set_ylabel("PC%s (%.1f%%)" % (y, perc_weights[y - 1]))
        ax.set_zlabel("PC%s (%.1f%%)" % (z, perc_weights[z - 1]))

        if "logx" in kargs and kargs["logx"]:
            ax.set_xscale("log", basex=kargs["logx"])
        if "logy" in kargs and kargs["logy"]:
            ax.set_yscale("log", basey=kargs["logy"])

        # squish_scales must be True as there seems to be a bug in 3D plots in guessing the scales
        # Don't worry about kargs, do_common_args will overwrite.
        ax.set_xlim([min(xdata), max(xdata)])
        ax.set_ylim([min(ydata), max(ydata)])
        ax.set_zlim([min(zdata), max(zdata)])

        #self.__draw.do_common_args(ax, **kargs)

        real_filename = self.__draw.savefigure(fig, filename)

        config.log.info(
            "scatter3d(): Saved 'PC%s' vs 'PC%s' vs 'PC%s' scatter to '%s'" %
            (x, y, z, real_filename))
Пример #30
0
    def scatter3d(self,
                  x,
                  y,
                  z,
                  filename=None,
                  spot_cols=None,
                  label=False,
                  stem=False,
                  label_font_size=6,
                  rotation=134,
                  elevation=48,
                  interactive=False,
                  squish_scales=False,
                  spot_size=40,
                  **kargs):
        """
        **Purpose**
            plot a scatter plot of PCx against PCy against PCz
            This is the 3D variant
                    
        **Arguments**
            x, y, z (Required)
                PC dimension to plot as scatter
                Note that PC begin at 1 (and not at zero, as might be expected)
        
            spot_cols (Optional, default="black" or self.set_cols())
                list of colours for the samples, should be the same length as 
                the number of conditions. 
                
            spot_size (Optional, default=40)
                The relative spot size.
            
            label (Optional, default=False)
                label each spot with the name of the condition
            
            label_font_size (Optional, default=6)
                label font size.
            
            stem (Optional, default=False)
                Draw stems from the spot down to the base of the graph. (i.e. z=0)
                
            rotation (Optional, default=134)
                The rotation along the X, Y plane
                
            elevation (Optional, default=48
                The rotation along the Z plane.
                
            interactive (Optional, default=False)
                if True then spawn the matplotlib show() view. Note that this will pause
                execution of your script.
                Note that by default glbase uses a non-GUI matplotlib setting.
                
                You will need to fiddle around with matplotlib.use() before importing glbase         
            
            squish_scales (Optional, default=False)
                set the limits very aggressively to [minmax(x), minmax(y), minmax(z)]
        
        **Returns**
            None
            You can get PC data from pca.get_uvd()
        """
        assert filename, "scatter(): Must provide a filename"

        xdata = self.__v[x - 1]
        ydata = self.__v[y - 1]
        zdata = self.__v[z - 1]

        fig = self.__draw.getfigure(**kargs)
        ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=elevation, azim=rotation)

        cols = self.cols
        if spot_cols:
            cols = spot_cols

        ax.scatter(xdata, ydata, zdata, edgecolors="none", c=cols, s=spot_size)
        if label:
            for i, lab in enumerate(self.labels):
                ax.text(xdata[i],
                        ydata[i],
                        zdata[i],
                        lab,
                        size=label_font_size,
                        ha="center",
                        va="bottom")

        if stem:  # stem must go after scatter for sorting. Actually, not true right? matplotlib uses zorder for that...
            z_min = min(zdata)
            for x_, y_, z_ in zip(xdata, ydata, zdata):
                line = art3d.Line3D(*list(zip((x_, y_, z_min), (x_, y_, z_))),
                                    marker=None,
                                    c="grey",
                                    alpha=0.1)
                ax.add_line(line)

        ax.set_xlabel("PC%s" % (x, ))  # can be overridden via do_common_args()
        ax.set_ylabel("PC%s" % (y, ))
        ax.set_zlabel("PC%s" % (z, ))

        if "logx" in kargs and kargs["logx"]:
            ax.set_xscale("log", basex=kargs["logx"])
        if "logy" in kargs and kargs["logy"]:
            ax.set_yscale("log", basey=kargs["logy"])

        if squish_scales:
            # Don't worry about kargs, do_common_args will overwrite.
            ax.set_xlim([min(xdata), max(xdata)])
            ax.set_ylim([min(ydata), max(ydata)])
            ax.set_zlim([min(zdata), max(zdata)])

        self.__draw.do_common_args(ax, **kargs)
        if "zlims" in kargs:
            ax.set_zlim([kargs["zlim"][0], kargs["zlim"][1]])

        if interactive:
            fig.show()  # hope you are not on a cluster!

        real_filename = self.__draw.savefigure(fig, filename)

        config.log.info(
            "scatter3d(): Saved 'PC%s' vs 'PC%s' vs 'PC%s' scatter to '%s'" %
            (x, y, z, real_filename))