コード例 #1
0
ファイル: addr_map.py プロジェクト: yzhe8769/cheriplot
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     # register the colors we use
     self._colors["load"] = colorConverter.to_rgba("#687a99", 1)
     self._colors["store"] = colorConverter.to_rgba("#895106", 1)
     self._markers = {
         "load": MarkerStyle(","),
         "store": MarkerStyle(","),
     }
コード例 #2
0
def plot_weather():
    if len(w_data):
        if opts.weather:
            ax_weather = ax.twinx()
            ax_weather.set_ylabel('Temperature (C) red: External Temp, purple: Internal SmartBox', color='r')
            ax_weather.set_ylim(range_temp_min, range_temp_max)
            ax_weather.set_yticks(np.arange(range_temp_min, range_temp_max, 5))
            ax_weather.set_yticklabels(np.arange(range_temp_min, range_temp_max, 5), color='r')
            ax_weather.plot(w_time, w_temp, color='r', lw=1.5, label='External Temp')
            ax_weather.tick_params(axis='y', labelcolor='r')
            ax_weather.spines["right"].set_position(("axes", 1.07))

            if opts.sbtemp:
                sb_tempi, sb_dati = get_sbtemp(t_start, t_stop)
                if sb_dati:
                    # ax_weather.plot(sb_tempi, sb_dati, color='purple', linestyle='None', marker=".", markersize=2, label='SmartBox Internal Temp')
                    ax_weather.plot(sb_tempi, sb_dati, color='purple', label='SmartBox Internal Temp',
                                    linestyle='None', marker=".", markersize=2)
                # else:
                #     print "\nNo SmartBox Temperature available!"
            # ax_weather.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1, ncol=8,#bbox_to_anchor=(1-0.2, 1-0.2)
            #                  loc="lower right", fontsize='small')

        if opts.wind:
            ax_wind = ax.twinx()
            ax_wind.plot(w_time, w_wind, color='orange', lw=2.5, linestyle='None', marker=".", markersize=3)
            ax_wind.set_ylim(0, 100)
            ax_wind.set_ylabel('Wind (Km/h)', color='orange')
            ax_wind.tick_params(axis='y', labelcolor='orange')
            ax_wind.spines["right"].set_position(("axes", 1.16))
            # Draw wind direction
            for a in range(len(w_wdir)):
                if not a % (len(w_wdir) / 24):
                    m = MarkerStyle(">")
                    m._transform.rotate_deg(w_wdir[a])
                    # print a, xticks[a], w_wind[a], len(xticks), len(w_wind)
                    ax_wind.scatter(w_time[a], w_wind[a], marker=m, s=20, color='black')
                    m = MarkerStyle("_")
                    m._transform.rotate_deg(w_wdir[a])
                    ax_wind.scatter(w_time[a], w_wind[a], marker=m, s=100, color='black')

        if opts.rain:
            ax_rain = ax.twinx()
            ax_rain.plot(w_time, w_rain, color='cyan', lw=3)
            ax_rain.set_ylim(0, 100)
            ax_rain.set_ylabel('Rain (mm)', color='cyan')
            ax_rain.tick_params(axis='y', labelcolor='cyan')
            ax_rain.spines["right"].set_position(("axes", 1.24))

        if opts.sun:
            if len(sun_data):
                ax_sun = ax.twinx()
                ax_sun.plot(sun_time, sun_data, color='k', lw=1.5)
                ax_sun.set_ylim(0, 4000)
                ax_sun.set_ylabel('Solar Radiation (W/m^2)', color='k')
                ax_sun.tick_params(axis='y', labelcolor='k')
                ax_sun.spines["right"].set_position(("axes", 1.32))
コード例 #3
0
def random_iteration(num_points):
    x = np.empty(0)
    y = np.empty(0)

    xk = 0
    yk = 0

    for _ in range(num_points + 1):
        var = random.randint(1, 12)

        if var > 0 and var <= 3:
            xk, yk = F1(xk, yk)
            x = np.append(x, xk)
            y = np.append(y, yk)

        if var > 3 and var <= 6:
            xk, yk = F2(xk, yk)
            x = np.append(x, xk)
            y = np.append(y, yk)

        if var > 6 and var <= 9:
            xk, yk = F3(xk, yk)
            x = np.append(x, xk)
            y = np.append(y, yk)

        if var > 9:
            xk, yk = F4(xk, yk)
            x = np.append(x, xk)
            y = np.append(y, yk)

    plt.figure(0)
    plt.scatter(x, y, s=0.01, marker=MarkerStyle(marker='*'))

    plt.axis('equal', xmin=-0.1, xmax=1.1, ymin=-0.2, ymax=1.2)
コード例 #4
0
def random_iteration(num_iters):
    x = np.empty(0)
    y = np.empty(0)

    xk = 0
    yk = 0

    for _ in range(num_iters + 1):
        var = random.randint(1, 100)

        if var == 1:
            xk, yk = F1(xk, yk)
            x = np.append(x, xk)
            y = np.append(y, yk)

        if var > 1 and var <= 86:
            xk, yk = F2(xk, yk)
            x = np.append(x, xk)
            y = np.append(y, yk)

        if var > 86 and var <= 92:
            xk, yk = F3(xk, yk)
            x = np.append(x, xk)
            y = np.append(y, yk)

        if var > 92:
            xk, yk = F4(xk, yk)
            x = np.append(x, xk)
            y = np.append(y, yk)

    plt.scatter(x, y, s=0.01, c='green', marker=MarkerStyle(marker='*'))

    plt.axis('equal', xmin=-0.1, xmax=1.1, ymin=-0.2, ymax=1.2)
コード例 #5
0
def random_iteration(num_points):
    x = np.empty(0)
    y = np.empty(0)

    xk = 0
    yk = 0

    for _ in range(num_points + 1):
        var = random.randint(1, 12)

        if var <= 4:
            xk, yk = F1(xk, yk)
            x = np.append(x, xk)
            y = np.append(y, yk)

        if var > 4 and var <= 8:
            xk, yk = F2(xk, yk)
            x = np.append(x, xk)
            y = np.append(y, yk)

        if var > 8:
            xk, yk = F3(xk, yk)
            x = np.append(x, xk)
            y = np.append(y, yk)

    plt.figure(0)
    plt.scatter(x, y, s=0.005, marker=MarkerStyle(marker='*'))
コード例 #6
0
def test_markerfacecolor_fillstyle():
    """Test that markerfacecolor does not override fillstyle='none'."""
    l, = plt.plot([1, 3, 2],
                  marker=MarkerStyle('o', fillstyle='none'),
                  markerfacecolor='red')
    assert l.get_fillstyle() == 'none'
    assert l.get_markerfacecolor() == 'none'
コード例 #7
0
def plot_latent_distribution(encoder,
                             x_test,
                             y_test,
                             batch_size=128):
    """
    Display a 2D plot of the digit classes in the latent space.
    We are interested only in z, so we only need the encoder here.
    :param encoder: the encoder network
    :param x_test: test images
    :param y_test: test labels
    :param batch_size: size of the mini-batch
    """
    z_mean, _, _ = encoder.predict(x_test, batch_size=batch_size)
    plt.figure(figsize=(6, 6))

    markers = ('o', 'x', '^', '<', '>', '*', 'h', 'H', 'D', 'd', 'P', 'X', '8', 's', 'p')

    for i in np.unique(y_test):
        plt.scatter(z_mean[y_test == i, 0], z_mean[y_test == i, 1],
                    marker=MarkerStyle(markers[i], fillstyle='none'),
                    edgecolors='black')

    plt.xlabel("z[0]")
    plt.ylabel("z[1]")
    plt.show()
コード例 #8
0
 def plot_result(self, cluster, mean):
     fig = plt.figure()
     ax = fig.add_subplot(111)
     for i in range(len(cluster)):
         markers = MarkerStyle().markers
         marker = random.choice(list(markers.keys()))
         ax.scatter(cluster[i][:, 0].A.T, cluster[i][:, 1].A.T, marker=marker)
         ax.scatter(mean[i][0, 0], mean[i][0, 1], marker='+', s=500)
     plt.show()
コード例 #9
0
def test_marker_as_markerstyle():
    fig, ax = plt.subplots()
    line, = ax.plot([2, 4, 3], marker=MarkerStyle("D"))
    fig.canvas.draw()
    assert line.get_marker() == "D"

    # continue with smoke tests:
    line.set_marker("s")
    fig.canvas.draw()
    line.set_marker(MarkerStyle("o"))
    fig.canvas.draw()
    # test Path roundtrip
    triangle1 = Path([[-1., -1.], [1., -1.], [0., 2.], [0., 0.]], closed=True)
    line2, = ax.plot([1, 3, 2], marker=MarkerStyle(triangle1), ms=22)
    line3, = ax.plot([0, 2, 1], marker=triangle1, ms=22)

    assert_array_equal(line2.get_marker().vertices, triangle1.vertices)
    assert_array_equal(line3.get_marker().vertices, triangle1.vertices)
コード例 #10
0
ファイル: gaplot.py プロジェクト: Jravis/gaepsi
    def scatter(self, x, y, s, ax=None, fancy=False, **kwargs):
        """ takes data coordinate x, y and plot them to a data coordinate axes,
        s is the radius in data units. 
        When fancy is True, apply a radient filter so that the 
        edge is blent into the background; better with marker='o' or marker='+'. """
        X, Y, S = numpy.asarray([x, y, s])
        if ax is None: ax = self.default_axes

        def filter(image, dpi):
            # this is problematic if the marker is clipped.
            if image.shape[0] <= 1 and image.shape[1] <= 1: return image
            xgrad = 1.0 \
               - numpy.fabs(numpy.linspace(0, 2,
                  image.shape[0], endpoint=True) - 1.0)
            ygrad = 1.0 \
               - numpy.fabs(numpy.linspace(0, 2,
                  image.shape[1], endpoint=True) - 1.0)
            image[..., 3] *= xgrad[:, None]**0.5
            image[..., 3] *= ygrad[None, :]**0.5
            return image, 0, 0

        marker = kwargs.pop('marker', 'x')
        verts = kwargs.pop('verts', None)
        # to be API compatible
        if marker is None and not (verts is None):
            marker = (verts, 0)
            verts = None

        objs = []
        color = kwargs.pop('color', None)
        edgecolor = kwargs.pop('edgecolor', None)
        linewidth = kwargs.pop('linewidth', kwargs.pop('lw', None))

        marker_obj = MarkerStyle(marker)
        if not marker_obj.is_filled():
            edgecolor = color

        for x, y, r in numpy.nditer([X, Y, S], flags=['zerosize_ok']):
            path = marker_obj.get_path().transformed(
                marker_obj.get_transform().scale(r).translate(x, y))
            obj = PathPatch(
                path,
                facecolor=color,
                edgecolor=edgecolor,
                linewidth=linewidth,
                transform=ax.transData,
            )
            obj.set_alpha(1.0)
            if fancy:
                obj.set_agg_filter(filter)
                obj.rasterized = True
            objs += [obj]
            ax.add_artist(obj)
        ax.autoscale_view()

        return objs
コード例 #11
0
ファイル: grave.py プロジェクト: ivanov/grave
def _generate_node_artist(pos, styles, *, ax):
    N = len(pos)
    proto_node = next(iter(pos))

    x = np.zeros(N) * np.nan
    y = np.zeros(N) * np.nan
    properties = {
        k: [None] * N
        for k in styles[proto_node] if k in _VALID_NODE_STYLE
    }

    for j, node in enumerate(pos):
        x[j], y[j] = pos[node]
        for key, values in properties.items():
            values[j] = styles[node][key]

    key_map = {
        'size': 'sizes',
        'color': 'facecolors',
        'shape': 'marker',
        'width': 'linewidths',
        'edgecolor': 'edgecolors'
    }
    renamed_properties = {key_map[k]: v for k, v in properties.items()}

    markers = renamed_properties.pop('marker', None)

    if markers is None:
        paths = (MarkerStyle('o'), )
    else:
        paths = [MarkerStyle(m) for m in markers]
    paths = [p.get_path().transformed(p.get_transform()) for p in paths]

    offsets = np.column_stack([x, y])
    node_art = PathCollection(paths,
                              offsets=offsets,
                              transOffset=ax.transData,
                              **renamed_properties)
    node_art.set_transform(mtransforms.IdentityTransform())

    ax.add_collection(node_art)
    ax.autoscale_view()
    return node_art
コード例 #12
0
def plot_kite(ax, beta, phi, psi=np.pi):
    y, z = calc_proj(beta, phi)
    psi_proj = corrected_orientation_angle(beta, phi, psi)[2]
    t = MarkerStyle(marker=7)
    t._transform = t.get_transform().rotate_deg(psi_proj * 180. / np.pi)
    marker_obj = ax.plot(y,
                         z,
                         's',
                         marker=t,
                         ms=20,
                         mfc='None',
                         mew=2,
                         mec='k')[0]
コード例 #13
0
    def _html_args(self):
        transform = self.line.get_transform() - self.ax.transData
        data = transform.transform(self.line.get_xydata()).tolist()

        markerstyle = MarkerStyle(self.line.get_marker())
        markersize = self.line.get_markersize()
        markerpath = path_data(markerstyle.get_path(),
                               (markerstyle.get_transform()
                                + Affine2D().scale(markersize, -markersize)))

        return dict(lineid=self.lineid,
                    data=json.dumps(data),
                    markerpath=json.dumps(markerpath))
コード例 #14
0
def run_2():
    fig = plt.figure(constrained_layout=False, frameon=False)
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_facecolor((0.37, 0.37, 0.35))

    n_rows = 2
    n_flowers = 5
    gs = GridSpec(n_rows, n_flowers, figure=fig, wspace=0, hspace=0.05)
    axes = []
    for i in range(n_rows):
        for j in range(n_flowers):
            axes.append(fig.add_subplot(gs[i, j], projection='polar'))

    n_points = 100
    rand_color = randomcolor.RandomColor()
    hue = "yellow"

    for ax in axes:

        stem_color = np.array(rand_color.generate(hue="green",
                                                  luminosity="dark",
                                                  count=1,
                                                  format_='Array_rgb')) / 256.

        flower_background_color = np.array(
            rand_color.generate(hue="yellow", luminosity="dark", count=1, format_='Array_rgb')) / 256.
        flower_background_color = flower_background_color[0]

        all_colors_rgb = np.array(rand_color.generate(hue=hue,
                                                      count=n_points,
                                                      format_='Array_rgb')) / 256.
        all_colors_hsv = np.array([color.rgb2hsv(tmp_color) for tmp_color in all_colors_rgb])
        all_colors_hsv[:, 2] *= np.linspace(0.3, 0.9, n_points)

        all_colors_rgb = color.hsv2rgb(all_colors_hsv)

        r = 1.5 * np.arange(n_points)
        radial_freq = np.random.randint(1, 3)
        theta = np.random.uniform(0, 360) + np.arange(n_points) * radial_freq
        area = 0.08 * r ** 1.8

        ax.set_facecolor(flower_background_color)
        ax.set_thetagrids([270], labels='l', fontsize=40, color=stem_color[0])
        ax.set_rgrids([])
        ax.set_frame_on(False)
        marker = MarkerStyle(marker='o',
                             # fillstyle='bottom'
                             )
        ax.scatter(theta, r, c=all_colors_rgb, s=area, cmap='hsv', alpha=0.95, marker=marker)
    plt.tight_layout()
    plt.show()
コード例 #15
0
    def visualize_simulation(self):

        plt.xlim(-self.window_w, self.window_w)
        plt.ylim(-self.window_h, self.window_h)
        plt.scatter(self.objects[:, 0],
                    self.objects[:, 1],
                    s=self.objects[:, -1]**2,
                    alpha=0.5,
                    c='b')
        plt.scatter(self.food[0], self.food[1], s=self.food[2], c='g')

        m = MarkerStyle('^')
        m._transform.rotate_deg(np.degrees(self.agent[2]) - 90)
        plt.scatter(self.agent[0], self.agent[1], marker=m, c='r', s=100)

        plt.pause(0.0001)
        plt.clf()
コード例 #16
0
def get_marker_style(line):
    """Get the style dictionary for matplotlib marker objects"""
    style = {}
    style['alpha'] = line.get_alpha()
    if style['alpha'] is None:
        style['alpha'] = 1

    style['facecolor'] = color_to_hex(line.get_markerfacecolor())
    style['edgecolor'] = color_to_hex(line.get_markeredgecolor())
    style['edgewidth'] = line.get_markeredgewidth()

    style['marker'] = line.get_marker()
    markerstyle = MarkerStyle(line.get_marker())
    markersize = line.get_markersize()
    markertransform = (markerstyle.get_transform() +
                       Affine2D().scale(markersize, -markersize))
    style['markerpath'] = SVG_path(markerstyle.get_path(), markertransform)
    style['zorder'] = line.get_zorder()
    return style
コード例 #17
0
    def get_patches(self, ax):
        ranges = LineCollection(self._cap_ranges, linestyle="solid")
        links = LineCollection(self._oob_links,
                               linestyle="dotted",
                               colors=colorConverter.to_rgba_array("#808080"))

        color = colorConverter.to_rgba_array("#DC143C")
        scales = np.array((20, ))
        marker_obj = MarkerStyle("o")
        path = marker_obj.get_path().transformed(marker_obj.get_transform())

        offsets = PathCollection((path, ),
                                 scales,
                                 facecolors=color,
                                 offsets=self._oob_offsets,
                                 transOffset=ax.transData)
        offsets.set_transform(IdentityTransform())

        return [ranges, links, offsets]
コード例 #18
0
def get_marker_style(line):
    """Get the style dictionary for matplotlib marker objects"""
    style = {}
    style["alpha"] = line.get_alpha()
    if style["alpha"] is None:
        style["alpha"] = 1

    style["facecolor"] = export_color(line.get_markerfacecolor())
    style["edgecolor"] = export_color(line.get_markeredgecolor())
    style["edgewidth"] = line.get_markeredgewidth()

    style["marker"] = line.get_marker()
    markerstyle = MarkerStyle(line.get_marker())
    markersize = line.get_markersize()
    markertransform = markerstyle.get_transform() + Affine2D().scale(
        markersize, -markersize)
    style["markerpath"] = SVG_path(markerstyle.get_path(), markertransform)
    style["markersize"] = markersize
    style["zorder"] = line.get_zorder()
    return style
コード例 #19
0
    def update_from(self, other):
        """copy properties from other to self"""
        Artist.update_from(self, other)
        self._linestyle = other._linestyle
        self._linewidth = other._linewidth
        self._color = other._color
        self._markersize = other._markersize
        self._markerfacecolor = other._markerfacecolor
        self._markerfacecoloralt = other._markerfacecoloralt
        self._markeredgecolor = other._markeredgecolor
        self._markeredgewidth = other._markeredgewidth
        self._dashSeq = other._dashSeq
        self._dashcapstyle = other._dashcapstyle
        self._dashjoinstyle = other._dashjoinstyle
        self._solidcapstyle = other._solidcapstyle
        self._solidjoinstyle = other._solidjoinstyle

        self._linestyle = other._linestyle
        self._marker = MarkerStyle(other._marker.get_marker(),
                                   other._marker.get_fillstyle())
        self._drawstyle = other._drawstyle
コード例 #20
0
def compare_val_trajectories(
    *dfs,
    eplen=None,
    delay_show=False,
):
    # styles_head = dict(marker='.', lw=1.5, ls='-', markersize=10, alpha=0.67, c='k',)
    # styles_last = dict(marker='^', lw=1.5, ls='-', markersize=10, alpha=0.67, c='g',)
    styles = dict(
        lw=1.5,
        ls="-",
        markersize=8,
        alpha=0.75,
    )
    markers = (k for k in MarkerStyle().markers.keys() if k not in {".", ","})

    lrkeys_to_dfs = {(df.lr.max(), df.lr.mean()): df for df in dfs}

    for lrkey in sorted(lrkeys_to_dfs.keys()):
        df = lrkeys_to_dfs[lrkey]
        label = f"(max, avg) = ({lrkey[0]:.1e}, {lrkey[1]:.1e})"
        (df.val_losses.dropna() - df.val_losses.dropna().iloc[0]).plot(
            label=label,
            marker=next(markers),
            **styles,
        )

    plt.legend()
    # for df in dfs[:-1]:
    #     (df.val_losses.dropna()-df.val_losses.dropna().iloc[0]).plot(**styles_head)
    #
    # df = dfs[-1]
    # (df.val_losses.dropna()-df.val_losses.dropna().iloc[0]).plot(**styles_last)

    if eplen is not None:
        eplens = [e for e in range(eplen, int(plt.axis()[1]), eplen)]
        ax = plt.gca()
        [ax.axvline(ep, c="r", ls="--", lw=1) for ep in eplens]

    if not delay_show:
        plt.show()
コード例 #21
0
def random_iteration(num_points):
    x = np.empty(0)
    y = np.empty(0)

    xk = 0
    yk = 0

    for _ in range(num_points+1):
        var = random.randint(1, 10)

        if var <= 5:
            xk, yk = F1(xk, yk)
            x = np.append(x, xk)
            y = np.append(y, yk)

        if var > 5:
            xk, yk = F2(xk, yk)
            x = np.append(x, xk)
            y = np.append(y, yk)

    plt.figure(0)
    plt.scatter(x, y, s=0.01, c='r', marker=MarkerStyle(marker='*'))

    plt.axis('equal')
コード例 #22
0
def plot_arrow(longs,
               lats,
               distance,
               min_distance=0.0001,
               dotted=False,
               arrow_colour='k',
               dot_colour='k',
               lw=1):

    if dotted: plt.plot(longs, lats, '--', c=arrow_colour, lw=lw)
    else: plt.plot(longs, lats, c=arrow_colour, lw=lw)

    #plt.plot(longs[1],lats[1],'.',c=dot_colour,ms=10)

    if not dotted and distance > min_distance:

        angle = -np.arctan2(longs[1] - longs[0], lats[1] - lats[0]) * 180 / (
            np.pi)
        t = MarkerStyle(marker='^')
        t._transform = t.get_transform().rotate_deg(angle)
        plt.scatter(np.mean(longs),
                    np.mean(lats),
                    color=arrow_colour,
                    marker=t)  #(3, 0, angle))
コード例 #23
0
             alpha=0.1,
             width=0.0001,
             length_includes_head=True,
             shape='full',
             overhang=0,
             fc='k',
             ec='k')

ax.scatter(original_data.iloc[:, 0],
           original_data.iloc[:, 1],
           edgecolors='black',
           alpha=0.5,
           s=20,
           linewidths=1,
           label=labels[0],
           marker=MarkerStyle(marker='o', fillstyle='none'),
           facecolors='none')
ax.scatter(masked_data.iloc[:, 0],
           masked_data.iloc[:, 1],
           edgecolors='black',
           alpha=0.5,
           s=20,
           linewidths=1,
           label=labels[1],
           marker=MarkerStyle(marker='v', fillstyle='none'),
           facecolors='none')

# percentage variance explained
pve_pc1 = coeff_data[0][0] / sum(coeff_data[0]) * 100
pve_pc2 = coeff_data[0][1] / sum(coeff_data[0]) * 100
コード例 #24
0
    def __init__(
            self,
            xdata,
            ydata,
            linewidth=None,  # all Nones default to rc
            linestyle=None,
            color=None,
            marker=None,
            markersize=None,
            markeredgewidth=None,
            markeredgecolor=None,
            markerfacecolor=None,
            markerfacecoloralt='none',
            fillstyle=None,
            antialiased=None,
            dash_capstyle=None,
            solid_capstyle=None,
            dash_joinstyle=None,
            solid_joinstyle=None,
            pickradius=5,
            drawstyle=None,
            markevery=None,
            **kwargs):
        """
        Create a :class:`~matplotlib.lines.Line2D` instance with *x*
        and *y* data in sequences *xdata*, *ydata*.

        The kwargs are :class:`~matplotlib.lines.Line2D` properties:

        %(Line2D)s

        See :meth:`set_linestyle` for a decription of the line styles,
        :meth:`set_marker` for a description of the markers, and
        :meth:`set_drawstyle` for a description of the draw styles.

        """
        Artist.__init__(self)

        #convert sequences to numpy arrays
        if not iterable(xdata):
            raise RuntimeError('xdata must be a sequence')
        if not iterable(ydata):
            raise RuntimeError('ydata must be a sequence')

        if linewidth is None:
            linewidth = rcParams['lines.linewidth']

        if linestyle is None:
            linestyle = rcParams['lines.linestyle']
        if marker is None:
            marker = rcParams['lines.marker']
        if color is None:
            color = rcParams['lines.color']

        if markersize is None:
            markersize = rcParams['lines.markersize']
        if antialiased is None:
            antialiased = rcParams['lines.antialiased']
        if dash_capstyle is None:
            dash_capstyle = rcParams['lines.dash_capstyle']
        if dash_joinstyle is None:
            dash_joinstyle = rcParams['lines.dash_joinstyle']
        if solid_capstyle is None:
            solid_capstyle = rcParams['lines.solid_capstyle']
        if solid_joinstyle is None:
            solid_joinstyle = rcParams['lines.solid_joinstyle']

        if drawstyle is None:
            drawstyle = 'default'

        self._dashcapstyle = None
        self._dashjoinstyle = None
        self._solidjoinstyle = None
        self._solidcapstyle = None
        self.set_dash_capstyle(dash_capstyle)
        self.set_dash_joinstyle(dash_joinstyle)
        self.set_solid_capstyle(solid_capstyle)
        self.set_solid_joinstyle(solid_joinstyle)

        self._linestyles = None
        self._drawstyle = None
        self._linewidth = None
        self.set_linestyle(linestyle)
        self.set_drawstyle(drawstyle)
        self.set_linewidth(linewidth)

        self._color = None
        self.set_color(color)
        self._marker = MarkerStyle()
        self.set_marker(marker)

        self._markevery = None
        self._markersize = None
        self._antialiased = None

        self.set_markevery(markevery)
        self.set_antialiased(antialiased)
        self.set_markersize(markersize)

        self._dashSeq = None

        self._markeredgecolor = None
        self._markeredgewidth = None
        self._markerfacecolor = None
        self._markerfacecoloralt = None

        self.set_markerfacecolor(markerfacecolor)
        self.set_markerfacecoloralt(markerfacecoloralt)
        self.set_markeredgecolor(markeredgecolor)
        self.set_markeredgewidth(markeredgewidth)

        self.set_fillstyle(fillstyle)

        self.verticalOffset = None

        # update kwargs before updating data to give the caller a
        # chance to init axes (and hence unit support)
        self.update(kwargs)
        self.pickradius = pickradius
        self.ind_offset = 0
        if is_numlike(self._picker):
            self.pickradius = self._picker

        self._xorig = np.asarray([])
        self._yorig = np.asarray([])
        self._invalidx = True
        self._invalidy = True
        self.set_data(xdata, ydata)
コード例 #25
0
#T# plot the figure
plt.plot(list1, list2, 'k')
arc1 = mpatches.Arc(p0, l1, l1, theta1=a1_0, theta2=a2_0)
arc2 = mpatches.Arc(p1, l1, l1, theta1=a2_1, theta2=a0_1)
arc3 = mpatches.Arc(p2, l1, l1, theta1=a0_2, theta2=a1_2)
ax1.add_patch(arc1)
ax1.add_patch(arc2)
ax1.add_patch(arc3)

#T# set the math text font to the Latex default, Computer Modern
import matplotlib
matplotlib.rcParams['mathtext.fontset'] = 'cm'

#T# create the markers
marker1 = MarkerStyle(r'$|$')
marker1._transform.scale(1, 2.2)
marker1._transform.rotate_deg((a1_0 + a2_0) / 2 + 90)

marker2 = MarkerStyle(r'$|$')
marker2._transform.scale(1, 2.2)
marker2._transform.rotate_deg((a0_1 + a2_1) / 2 + 90)

marker3 = MarkerStyle(r'$|$')
marker3._transform.scale(1, 2.2)
marker3._transform.rotate_deg((a1_2 + a0_2) / 2 + 90)

#T# plot the markers
plt.plot(p0_marker[0], p0_marker[1], 'k', marker=marker1)
plt.plot(p1_marker[0], p1_marker[1], 'k', marker=marker2)
plt.plot(p2_marker[0], p2_marker[1], 'k', marker=marker3)
コード例 #26
0
def draw_pathcollection(data, obj):
    """Returns PGFPlots code for a number of patch objects."""
    content = []
    # gather data
    assert obj.get_offsets() is not None
    labels = ["x" + 21 * " ", "y" + 21 * " "]
    dd = obj.get_offsets()

    draw_options = ["only marks"]
    table_options = []

    if obj.get_array() is not None:
        draw_options.append("scatter")
        dd = numpy.column_stack([dd, obj.get_array()])
        labels.append("colordata" + 13 * " ")
        draw_options.append("scatter src=explicit")
        table_options.extend(["x=x", "y=y", "meta=colordata"])
        ec = None
        fc = None
        ls = None
        marker0 = None
    else:
        # gather the draw options
        try:
            ec = obj.get_edgecolors()[0]
        except (TypeError, IndexError):
            ec = None

        try:
            fc = obj.get_facecolors()[0]
        except (TypeError, IndexError):
            fc = None

        try:
            ls = obj.get_linestyle()[0]
        except (TypeError, IndexError):
            ls = None

        # "solution" from
        # <https://github.com/matplotlib/matplotlib/issues/4672#issuecomment-378702670>
        p = obj.get_paths()[0]
        ms = {style: MarkerStyle(style) for style in MarkerStyle.markers}
        paths = {
            style: marker.get_path().transformed(marker.get_transform())
            for style, marker in ms.items()
        }
        marker0 = None
        for marker, path in paths.items():
            if (numpy.array_equal(path.codes, p.codes)
                    and (path.vertices.shape == p.vertices.shape)
                    and numpy.max(
                        numpy.abs(path.vertices - p.vertices)) < 1.0e-10):
                marker0 = marker
                break

    is_contour = len(dd) == 1
    if is_contour:
        draw_options = ["draw=none"]

    if marker0 is not None:
        data, pgfplots_marker, marker_options = _mpl_marker2pgfp_marker(
            data, marker0, fc)
        draw_options += [f"mark={pgfplots_marker}"]
        if marker_options:
            draw_options += [
                "mark options={{{}}}".format(",".join(marker_options))
            ]

    # `only mark` plots don't need linewidth
    data, extra_draw_options = get_draw_options(data, obj, ec, fc, ls, None)
    draw_options += extra_draw_options

    if obj.get_cmap():
        mycolormap, is_custom_cmap = _mpl_cmap2pgf_cmap(obj.get_cmap(), data)
        draw_options.append("colormap" + ("=" if is_custom_cmap else "/") +
                            mycolormap)

    legend_text = get_legend_text(obj)
    if legend_text is None and has_legend(obj.axes):
        draw_options.append("forget plot")

    for path in obj.get_paths():
        if is_contour:
            dd = path.vertices

        if len(obj.get_sizes()) == len(dd):
            # See Pgfplots manual, chapter 4.25.
            # In Pgfplots, \mark size specifies raddi, in matplotlib circle areas.
            radii = numpy.sqrt(obj.get_sizes() / numpy.pi)
            dd = numpy.column_stack([dd, radii])
            labels.append("sizedata" + 14 * " ")
            draw_options.extend([
                "visualization depends on=" +
                "{\\thisrow{sizedata} \\as\\perpointmarksize}",
                "scatter/@pre marker code/.append style=" +
                "{/tikz/mark size=\\perpointmarksize}",
            ])

        do = " [{}]".format(", ".join(draw_options)) if draw_options else ""
        content.append(f"\\addplot{do}\n")

        to = " [{}]".format(", ".join(table_options)) if table_options else ""
        content.append(f"table{to}{{%\n")

        content.append((" ".join(labels)).strip() + "\n")
        ff = data["float format"]
        fmt = (" ".join(dd.shape[1] * ["{:" + ff + "}"])) + "\n"
        for d in dd:
            content.append(fmt.format(*tuple(d)))
        content.append("};\n")

    if legend_text is not None:
        content.append(f"\\addlegendentry{{{legend_text}}}\n")

    return data, content
コード例 #27
0
# ============================================
#
# Markers can be modified by passing a transform to the MarkerStyle
# constructor. Following example shows how a supplied rotation is applied to
# several marker shapes.

common_style = {k: v for k, v in filled_marker_style.items() if k != 'marker'}
angles = [0, 10, 20, 30, 45, 60, 90]

fig, ax = plt.subplots()
fig.suptitle('Rotated markers', fontsize=14)

ax.text(-0.5, 0, 'Filled marker', **text_style)
for x, theta in enumerate(angles):
    t = Affine2D().rotate_deg(theta)
    ax.plot(x, 0, marker=MarkerStyle('o', 'left', t), **common_style)

ax.text(-0.5, 1, 'Un-filled marker', **text_style)
for x, theta in enumerate(angles):
    t = Affine2D().rotate_deg(theta)
    ax.plot(x, 1, marker=MarkerStyle('1', 'left', t), **common_style)

ax.text(-0.5, 2, 'Equation marker', **text_style)
for x, theta in enumerate(angles):
    t = Affine2D().rotate_deg(theta)
    eq = r'$\frac{1}{x}$'
    ax.plot(x, 2, marker=MarkerStyle(eq, 'left', t), **common_style)

for x, theta in enumerate(angles):
    ax.text(x, 2.5, f"{theta}°", horizontalalignment="center")
format_axes(ax)
コード例 #28
0
def plot():

    #EW vs SPT:

    fig = plt.figure(figsize=(12, 8))
    plt.subplots_adjust(hspace=0.001)
    P1 = plt.subplot(221)
    plt.ylim(0, 12)
    plt.xlim(9.5, 19.5)
    plt.ylabel("1.1693 $\mu$m EW")
    plt.xlabel("Spectral Type")
    for n in range(len(spt)):
        if FirstEW[n] != 0:
            plt.errorbar(spt[n],
                         FirstEW[n],
                         yerr=FirstEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            sc1 = plt.scatter(spt[n],
                              FirstEW[n],
                              alpha=0.9,
                              s=marker_size[n],
                              c=JK_dev[n],
                              vmin=-std,
                              vmax=std,
                              cmap='coolwarm',
                              zorder=1,
                              marker=MarkerStyle(marker_style[n],
                                                 fillstyle='full'))
        else:
            pass
    #plt.colorbar(sc1)
    plt.errorbar(spt_ML,
                 FirstEW_ML,
                 yerr=FirstEW_err_ML,
                 fmt='none',
                 alpha=.9,
                 zorder=-1,
                 linestyle='None',
                 ecolor='grey',
                 elinewidth=2)
    plt.scatter(spt_ML,
                FirstEW_ML,
                alpha=0.4,
                s=120,
                c='k',
                zorder=1,
                marker='^')
    plt.xticks(np.arange(9, 20, 1))
    P1.set_xticklabels(labels)
    plt.setp(P1.get_xticklabels(), visible=False)

    P2 = plt.subplot(222, sharex=P1)
    plt.ylim(2, 16)
    plt.xlim(9.5, 19.5)
    plt.ylabel("1.1773 $\mu$m EW")
    plt.xlabel("Spectral Type")

    for n in range(len(spt)):
        if SecondEW[n] != 0:
            plt.errorbar(spt[n],
                         SecondEW[n],
                         yerr=SecondEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            sc2 = plt.scatter(spt[n],
                              SecondEW[n],
                              alpha=0.9,
                              s=marker_size[n],
                              c=JK_dev[n],
                              vmin=-std,
                              vmax=std,
                              cmap='coolwarm',
                              zorder=1,
                              marker=MarkerStyle(marker_style[n],
                                                 fillstyle='full'))
        else:
            pass
    #plt.colorbar(sc2)
    plt.errorbar(spt_ML,
                 SecondEW_ML,
                 yerr=SecondEW_err_ML,
                 fmt='none',
                 alpha=.9,
                 zorder=-1,
                 linestyle='None',
                 ecolor='grey',
                 elinewidth=2)
    plt.scatter(spt_ML,
                SecondEW_ML,
                alpha=0.4,
                s=120,
                c='k',
                zorder=1,
                marker='^')
    plt.xticks(np.arange(9, 20, 1))
    P2.set_xticklabels(labels)
    plt.setp(P2.get_xticklabels(), visible=False)

    P3 = plt.subplot(223, sharex=P1)
    plt.ylim(0, 10)
    plt.xlim(9.5, 19.5)
    plt.ylabel("1.2436 $\mu$m EW")
    plt.xlabel("Spectral Type")
    for n in range(len(spt)):
        if ThirdEW[n] != 0:
            plt.errorbar(spt[n],
                         ThirdEW[n],
                         yerr=ThirdEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            sc3 = plt.scatter(spt[n],
                              ThirdEW[n],
                              alpha=0.9,
                              s=marker_size[n],
                              c=JK_dev[n],
                              vmin=-std,
                              vmax=std,
                              cmap='coolwarm',
                              zorder=1,
                              marker=MarkerStyle(marker_style[n],
                                                 fillstyle='full'))
        else:
            pass
    #plt.colorbar(sc3)
    plt.errorbar(spt_ML,
                 ThirdEW_ML,
                 yerr=ThirdEW_err_ML,
                 fmt='none',
                 alpha=.9,
                 zorder=-1,
                 linestyle='None',
                 ecolor='grey',
                 elinewidth=2)
    plt.scatter(spt_ML,
                ThirdEW_ML,
                alpha=0.4,
                s=120,
                c='k',
                zorder=1,
                marker='^')
    plt.xticks(np.arange(9, 20, 1))
    P3.set_xticklabels(labels)

    plt.legend((data1, data2, data3, data4, data5),
               ("Spec & Photo Pec", "Spectrally Pec", "Photometrically Pec",
                "Not Pec", "McLean et al. 2003"),
               fontsize=11,
               loc='lower left',
               numpoints=1)

    P4 = plt.subplot(224, sharex=P1)
    #plt.ylim(1.24,1.315)
    plt.xlim(9.5, 19.5)
    plt.ylabel("1.2525 $\mu$m EW")
    plt.xlabel("Spectral Type")
    for n in range(len(spt)):
        if FourthEW[n] != 0:
            plt.errorbar(spt[n],
                         FourthEW[n],
                         yerr=FourthEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            sc4 = plt.scatter(spt[n],
                              FourthEW[n],
                              alpha=0.9,
                              s=marker_size[n],
                              c=JK_dev[n],
                              vmin=-std,
                              vmax=std,
                              cmap='coolwarm',
                              zorder=1,
                              marker=MarkerStyle(marker_style[n],
                                                 fillstyle='full'))
        else:
            pass
    #plt.colorbar(sc4)
    plt.errorbar(spt_ML,
                 FourthEW_ML,
                 yerr=FourthEW_err_ML,
                 fmt='none',
                 alpha=.9,
                 zorder=-1,
                 linestyle='None',
                 ecolor='grey',
                 elinewidth=2)
    plt.scatter(spt_ML,
                FourthEW_ML,
                alpha=0.4,
                s=120,
                c='k',
                zorder=1,
                marker='^')
    plt.xticks(np.arange(9, 20, 1))
    P4.set_xticklabels(labels)

    fig.subplots_adjust(right=0.8)
    cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
    cbar = fig.colorbar(sc4, cax=cbar_ax)
    cbar.ax.get_yaxis().labelpad = 15
    cbar.ax.set_ylabel('$\Delta J-K_{s}$', rotation=270)

    #Subplots:

    # SPT
    fig1 = plt.figure(figsize=(12, 8))
    plt.subplots_adjust(hspace=0.001)
    ax1 = plt.subplot(221)
    plt.ylim(0, 12)
    plt.xlim(10, 19.5)
    plt.ylabel("1.1693 $\mu$m EW")
    plt.xlabel("Spectral Type")
    for n in range(len(spt)):
        if FirstEW[n] != 0:

            plt.errorbar(spt[n],
                         FirstEW[n],
                         yerr=FirstEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            plt.scatter(spt[n],
                        FirstEW[n],
                        alpha=0.9,
                        s=marker_size[n],
                        c='red',
                        zorder=1,
                        marker=MarkerStyle(marker_style[n], fillstyle='full'))
        else:
            pass
    plt.errorbar(spt_ML,
                 FirstEW_ML,
                 yerr=FirstEW_err_ML,
                 fmt='none',
                 alpha=.9,
                 zorder=-1,
                 linestyle='None',
                 ecolor='grey',
                 elinewidth=2)
    plt.scatter(spt_ML,
                FirstEW_ML,
                alpha=0.4,
                s=120,
                c='k',
                zorder=1,
                marker='^')
    plt.xticks(np.arange(9, 20, 1))
    ax1.set_xticklabels(labels)
    plt.setp(ax1.get_xticklabels(), visible=False)

    ax2 = plt.subplot(222)
    plt.ylim(2, 16)
    plt.xlim(10, 19.5)
    plt.ylabel("1.1773 $\mu$m EW")
    plt.xlabel("Spectral Type")
    for n in range(len(spt)):
        if SecondEW[n] != 0:
            plt.errorbar(spt[n],
                         SecondEW[n],
                         yerr=SecondEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            plt.scatter(spt[n],
                        SecondEW[n],
                        alpha=0.9,
                        s=marker_size[n],
                        c='red',
                        cmap='coolwarm',
                        zorder=1,
                        marker=MarkerStyle(marker_style[n], fillstyle='full'))
        else:
            pass
    plt.errorbar(spt_ML,
                 SecondEW_ML,
                 yerr=SecondEW_err_ML,
                 fmt='none',
                 alpha=.9,
                 zorder=-1,
                 linestyle='None',
                 ecolor='grey',
                 elinewidth=2)
    plt.scatter(spt_ML,
                SecondEW_ML,
                alpha=0.4,
                s=120,
                c='k',
                zorder=1,
                marker='^')
    plt.xticks(np.arange(9, 20, 1))
    ax2.set_xticklabels(labels)
    plt.setp(ax2.get_xticklabels(), visible=False)
    #
    ax3 = plt.subplot(223)
    plt.ylim(0.5, 11)
    plt.xlim(10, 19.5)
    plt.ylabel("1.2436 $\mu$m EW")
    plt.xlabel("Spectral Type")
    for n in range(len(spt)):
        if ThirdEW[n] != 0:

            plt.errorbar(spt[n],
                         ThirdEW[n],
                         yerr=ThirdEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            plt.scatter(spt[n],
                        ThirdEW[n],
                        alpha=0.9,
                        s=marker_size[n],
                        c='red',
                        cmap='coolwarm',
                        zorder=1,
                        marker=MarkerStyle(marker_style[n], fillstyle='full'))
        else:
            pass
    plt.errorbar(spt_ML,
                 ThirdEW_ML,
                 yerr=ThirdEW_err_ML,
                 fmt='none',
                 alpha=.9,
                 zorder=-1,
                 linestyle='None',
                 ecolor='grey',
                 elinewidth=2)
    plt.scatter(spt_ML,
                ThirdEW_ML,
                alpha=0.4,
                s=120,
                c='k',
                zorder=1,
                marker='^')
    plt.xticks(np.arange(9, 20, 1))
    ax3.set_xticklabels(labels)

    plt.legend((extra, data7, data8, data9, data10, data5),
               ("This work:", "Spec & Photo Pec", "Spectrally Pec",
                "Photometrically Pec", "Not Pec", "McLean et al. 2003"),
               fontsize=11,
               loc='lower left',
               numpoints=1)

    ax4 = plt.subplot(224)
    plt.ylim(0, 12)
    plt.xlim(10, 19.5)
    plt.ylabel("1.2525 $\mu$m EW")
    plt.xlabel("Spectral Type")
    for n in range(len(spt)):
        if FirstEW[n] != 0:
            plt.errorbar(spt[n],
                         FourthEW[n],
                         yerr=FourthEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            plt.scatter(spt[n],
                        FourthEW[n],
                        alpha=0.9,
                        s=marker_size[n],
                        c='red',
                        cmap='coolwarm',
                        zorder=1,
                        marker=MarkerStyle(marker_style[n], fillstyle='full'))
        else:
            pass
    plt.errorbar(spt_ML,
                 FourthEW_ML,
                 yerr=FourthEW_err_ML,
                 fmt='none',
                 alpha=.9,
                 zorder=-1,
                 linestyle='None',
                 ecolor='grey',
                 elinewidth=2)
    plt.scatter(spt_ML,
                FourthEW_ML,
                alpha=0.4,
                s=120,
                c='k',
                zorder=1,
                marker='^')
    plt.xticks(np.arange(9, 20, 1))
    ax4.set_xticklabels(labels)

    # JK
    fig2 = plt.figure(figsize=(12, 8))
    ax5 = plt.subplot(221)
    plt.subplots_adjust(hspace=0.001)
    plt.ylabel("1.1693 $\mu$m EW")
    plt.xlabel("$\Delta J-K_{s}$")
    for n in range(len(spt)):
        if FirstEW[n] != 0:
            plt.errorbar(JK_dev[n],
                         FirstEW[n],
                         yerr=FirstEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            plt.scatter(JK_dev[n],
                        FirstEW[n],
                        alpha=0.75,
                        s=marker_size[n],
                        c='white',
                        zorder=1,
                        marker=MarkerStyle(marker_style[n], fillstyle='full'))
        else:
            pass
    plt.setp(ax5.get_xticklabels(), visible=False)
    plt.legend((data1, data2, data3, data4),
               ("Spec & Photo Pec", "Spectrally Pec", "Photometrically Pec",
                "Not Pec"),
               fontsize=11,
               loc='lower left',
               numpoints=1)

    ax6 = plt.subplot(222)
    plt.ylabel("1.1773 $\mu$m EW")
    plt.xlabel("$\Delta J-K_{s}$")
    for n in range(len(spt)):
        if SecondEW[n] != 0:
            plt.errorbar(JK_dev[n],
                         SecondEW[n],
                         yerr=SecondEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            plt.scatter(JK_dev[n],
                        SecondEW[n],
                        alpha=0.75,
                        s=marker_size[n],
                        c='white',
                        cmap='coolwarm',
                        zorder=1,
                        marker=MarkerStyle(marker_style[n], fillstyle='full'))
        else:
            pass
    plt.setp(ax6.get_xticklabels(), visible=False)
    #
    ax7 = plt.subplot(223)
    plt.ylabel("1.2436 $\mu$m EW")
    plt.xlabel("$\Delta J-K_{s}$")
    for n in range(len(spt)):
        if ThirdEW[n] != 0:
            plt.errorbar(JK_dev[n],
                         ThirdEW[n],
                         yerr=ThirdEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            plt.scatter(JK_dev[n],
                        ThirdEW[n],
                        alpha=0.75,
                        s=marker_size[n],
                        zorder=1,
                        c='white',
                        marker=MarkerStyle(marker_style[n], fillstyle='full'))
        else:
            pass

    ax8 = plt.subplot(224)
    plt.ylabel("1.2525 $\mu$m EW")
    plt.xlabel("$\Delta J-K_{s}$")
    for n in range(len(spt)):
        if FirstEW[n] != 0:
            plt.errorbar(JK_dev[n],
                         FourthEW[n],
                         yerr=FourthEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            plt.scatter(JK_dev[n],
                        FourthEW[n],
                        alpha=0.75,
                        s=marker_size[n],
                        c='white',
                        zorder=1,
                        marker=MarkerStyle(marker_style[n], fillstyle='full'))
        else:
            pass

    # JH
    fig3 = plt.figure(figsize=(12, 8))
    ax9 = plt.subplot(221)
    plt.subplots_adjust(hspace=0.001)
    plt.ylabel("1.1693 $\mu$m EW")
    plt.xlabel("$\Delta J-H$")
    for n in range(len(spt)):
        if FirstEW[n] != 0:
            plt.errorbar(JH_dev[n],
                         FirstEW[n],
                         yerr=FirstEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            plt.scatter(JH_dev[n],
                        FirstEW[n],
                        alpha=0.75,
                        s=marker_size[n],
                        c=JK_dev[n],
                        vmin=-std,
                        vmax=std,
                        cmap='coolwarm',
                        zorder=1,
                        marker=MarkerStyle(marker_style[n], fillstyle='full'))
        else:
            pass
    plt.setp(ax9.get_xticklabels(), visible=False)
    plt.legend((data1, data2, data3, data4),
               ("Spec & Photo Pec", "Spectrally Pec", "Photometrically Pec",
                "Not Pec"),
               fontsize=11,
               loc='lower left',
               numpoints=1)

    ax10 = plt.subplot(222)
    plt.ylabel("1.1773 $\mu$m EW")
    plt.xlabel("$\Delta J-H$")
    for n in range(len(spt)):
        if SecondEW[n] != 0:
            plt.errorbar(JH_dev[n],
                         SecondEW[n],
                         yerr=SecondEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            plt.scatter(JH_dev[n],
                        SecondEW[n],
                        alpha=0.75,
                        s=marker_size[n],
                        c=JK_dev[n],
                        vmin=-std,
                        vmax=std,
                        cmap='coolwarm',
                        zorder=1,
                        marker=MarkerStyle(marker_style[n], fillstyle='full'))
        else:
            pass
    plt.setp(ax10.get_xticklabels(), visible=False)
    #
    ax11 = plt.subplot(223)
    plt.ylabel("1.2436 $\mu$m EW")
    plt.xlabel("$\Delta J-H$")
    for n in range(len(spt)):
        if ThirdEW[n] != 0:
            plt.errorbar(JH_dev[n],
                         ThirdEW[n],
                         yerr=ThirdEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            plt.scatter(JH_dev[n],
                        ThirdEW[n],
                        alpha=0.75,
                        s=marker_size[n],
                        zorder=1,
                        c=JK_dev[n],
                        vmin=-std,
                        vmax=std,
                        cmap='coolwarm',
                        marker=MarkerStyle(marker_style[n], fillstyle='full'))
        else:
            pass
#
    ax12 = plt.subplot(224)
    plt.ylabel("1.2525 $\mu$m EW")
    plt.xlabel("$\Delta J-H$")
    for n in range(len(spt)):
        if FirstEW[n] != 0:
            plt.errorbar(JH_dev[n],
                         FourthEW[n],
                         yerr=FourthEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            df1 = plt.scatter(JH_dev[n],
                              FourthEW[n],
                              alpha=0.75,
                              s=marker_size[n],
                              c=JK_dev[n],
                              vmin=-std,
                              vmax=std,
                              cmap='coolwarm',
                              zorder=1,
                              marker=MarkerStyle(marker_style[n],
                                                 fillstyle='full'))
        else:
            pass
    fig3.subplots_adjust(right=0.8)
    cbar_ax = fig3.add_axes([0.85, 0.15, 0.05, 0.7])
    cbar = fig3.colorbar(df1, cax=cbar_ax)
    cbar.ax.get_yaxis().labelpad = 15
    cbar.ax.set_ylabel('$\Delta J-K_{s}$', rotation=270)

    # HK
    fig4 = plt.figure(figsize=(12, 8))
    ax13 = plt.subplot(221)
    plt.subplots_adjust(hspace=0.001)
    plt.ylabel("1.1693 $\mu$m EW")
    plt.xlabel("$\Delta H-K_{s}$")
    for n in range(len(spt)):
        if FirstEW[n] != 0:
            plt.errorbar(HK_dev[n],
                         FirstEW[n],
                         yerr=FirstEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            plt.scatter(HK_dev[n],
                        FirstEW[n],
                        alpha=0.75,
                        s=marker_size[n],
                        c=JK_dev[n],
                        vmin=-std,
                        vmax=std,
                        cmap='coolwarm',
                        zorder=1,
                        marker=MarkerStyle(marker_style[n], fillstyle='full'))
        else:
            pass
    plt.setp(ax13.get_xticklabels(), visible=False)
    plt.legend((data1, data2, data3, data4),
               ("Spec & Photo Pec", "Spectrally Pec", "Photometrically Pec",
                "Not Pec"),
               fontsize=11,
               loc='lower left',
               numpoints=1)

    ax14 = plt.subplot(222)
    plt.ylabel("1.1773 $\mu$m EW")
    plt.xlabel("$\Delta H-K_{s}$")
    for n in range(len(spt)):
        if SecondEW[n] != 0:
            plt.errorbar(HK_dev[n],
                         SecondEW[n],
                         yerr=SecondEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            plt.scatter(HK_dev[n],
                        SecondEW[n],
                        alpha=0.75,
                        s=marker_size[n],
                        c=JK_dev[n],
                        vmin=-std,
                        vmax=std,
                        cmap='coolwarm',
                        zorder=1,
                        marker=MarkerStyle(marker_style[n], fillstyle='full'))
        else:
            pass
    plt.setp(ax14.get_xticklabels(), visible=False)
    #
    ax15 = plt.subplot(223)
    plt.ylabel("1.2436 $\mu$m EW")
    plt.xlabel("$\Delta H-K_{s}$")
    for n in range(len(spt)):
        if ThirdEW[n] != 0:
            plt.errorbar(HK_dev[n],
                         ThirdEW[n],
                         yerr=ThirdEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            plt.scatter(HK_dev[n],
                        ThirdEW[n],
                        alpha=0.75,
                        s=marker_size[n],
                        zorder=1,
                        c=JK_dev[n],
                        vmin=-std,
                        vmax=std,
                        cmap='coolwarm',
                        marker=MarkerStyle(marker_style[n], fillstyle='full'))
        else:
            pass
#
    ax16 = plt.subplot(224)
    plt.ylabel("1.2525 $\mu$m EW")
    plt.xlabel("$\Delta H-K_{s}$")
    for n in range(len(spt)):
        if FirstEW[n] != 0:
            plt.errorbar(JK_dev[n],
                         FourthEW[n],
                         yerr=FourthEW_err[n],
                         fmt='none',
                         alpha=.9,
                         zorder=-1,
                         linestyle='None',
                         ecolor='grey',
                         elinewidth=2)
            df2 = plt.scatter(JK_dev[n],
                              FourthEW[n],
                              alpha=0.75,
                              s=marker_size[n],
                              c=JK_dev[n],
                              vmin=-std,
                              vmax=std,
                              cmap='coolwarm',
                              zorder=1,
                              marker=MarkerStyle(marker_style[n],
                                                 fillstyle='full'))
        else:
            pass
    fig4.subplots_adjust(right=0.8)
    cbar_ax = fig4.add_axes([0.85, 0.15, 0.05, 0.7])
    cbar = fig4.colorbar(df2, cax=cbar_ax)
    cbar.ax.get_yaxis().labelpad = 15
    cbar.ax.set_ylabel('$\Delta J-K_{s}$', rotation=270)
コード例 #29
0
    def Draw(self, products, micapsfile, debug=True):
        """
        根据产品参数绘制图像
        :param micapsfile: 指定绘制产品中包含的一个micapsfile
        :param debug: 调试状态
        :param products: 产品参数 
        :return: 
        """
        self.UpdateData(products, micapsfile)
        extents = products.picture.extents
        xmax = extents.xmax
        xmin = extents.xmin
        ymax = extents.ymax
        ymin = extents.ymin

        # 设置绘图画板的宽和高 单位:英寸
        h = products.picture.height
        if products.map.projection.name == 'sall':  # 等经纬度投影时不用配置本身的宽度,直接根据宽高比得到
            w = h * np.math.fabs(
                (xmax - xmin) / (ymax - ymin)) * products.picture.widthshrink
        else:
            w = products.picture.width

        # 创建画布
        fig = plt.figure(figsize=(w, h),
                         dpi=products.picture.dpi,
                         facecolor="white")  # 必须在前面
        ax = fig.add_subplot(111)
        ax.spines['bottom'].set_linewidth(products.map.projection.axisthick)
        ax.spines['left'].set_linewidth(products.map.projection.axisthick)
        ax.spines['right'].set_linewidth(products.map.projection.axisthick)
        ax.spines['top'].set_linewidth(products.map.projection.axisthick)
        # 设置绘图区域
        plt.xlim(xmin, xmax)
        plt.ylim(ymin, ymax)

        # 背景透明
        fig.patch.set_alpha(products.picture.opacity)

        # 坐标系统尽可能靠近绘图区边界
        fig.tight_layout(pad=products.picture.pad)

        clipborder = products.map.clipborders[0]

        # 获得产品投影
        from Projection import Projection
        m = Projection.GetProjection(products)

        if m is not plt:
            # 用投影更新经纬度数据
            self.X, self.Y = Micaps.UpdateXY(m, self.X, self.Y)
            # 用投影更新产品参数中涉及经纬度的数据
            Micaps.Update(products, m)
            # 画世界底图
            Map.DrawWorld(products, m)

        # 绘制裁切区域边界
        patch = Map.DrawClipBorders(products.map.clipborders)

        # draw parallels and meridians.
        Map.DrawGridLine(products, m)

        cmap = nclcmaps.cmaps(
            micapsfile.legend.micapslegendcolor)  # cm.jet  temp_diff_18lev
        vmax = math.ceil(self.max)
        vmin = math.floor(self.min)
        levels = arange(vmin - self.distance, vmax + self.distance + 0.1,
                        self.distance)

        if micapsfile.legend.micapslegendvalue:
            level = levels
        else:
            level = micapsfile.legend.legendvalue

        # 绘制等值线 ------ 等值线和标注是一体的
        c = micapsfile.contour

        Map.DrawContourAndMark(contour=c,
                               x=self.X,
                               y=self.Y,
                               z=self.Z,
                               level=level,
                               clipborder=clipborder,
                               patch=patch,
                               m=m)

        cf = micapsfile.contour
        cbar = micapsfile.legend
        extend = micapsfile.legend.extend
        # 绘制色斑图 ------ 色版图、图例、裁切是一体的
        Map.DrawContourfAndLegend(contourf=cf,
                                  legend=cbar,
                                  clipborder=clipborder,
                                  patch=patch,
                                  cmap=cmap,
                                  levels=levels,
                                  extend=extend,
                                  extents=extents,
                                  x=self.X,
                                  y=self.Y,
                                  z=self.Z,
                                  m=m)

        # 绘制描述文本
        MicapsFile.MicapsFile.DrawTitle(m, micapsfile.title, self.title)

        self.DrawUV(m, micapsfile, clipborder, patch)

        # 绘制地图
        Map.DrawBorders(m, products)

        # 绘制散点
        if micapsfile.contour.scatter:
            if hasattr(self, 'x1'):
                m.scatter(self.x1,
                          self.y1,
                          s=micapsfile.contour.radius,
                          c=self.z1,
                          alpha=micapsfile.contour.alpha,
                          edgecolors='b')
            else:
                m.scatter(self.X,
                          self.Y,
                          s=micapsfile.contour.radius,
                          c=self.Z,
                          alpha=micapsfile.contour.alpha,
                          edgecolors='b')

        # 绘制站点
        stations = products.map.stations
        if stations.visible:
            # 'code': code, 'lon': lon, 'lat': lat, 'height': height,
            # 'iclass': iclass, 'infosum': infosum, 'name': info[0]
            # stations_tuple = tuple(stations.micapsdata.stations)
            # (code, lat, lon, height, iclass, infosum, info[0])
            # stations_array = np.array(stations.micapsdata.stations, dtype=[
            #     ('code', 'U'),
            #     ('lat', np.float32),
            #     ('lon', np.float32),
            #     ('height', np.float32),
            #     ('iclass', 'i'),
            #     ('infosum', 'i'),
            #     ('info', 'U')
            # ])

            # stations_array = [list(ele) for ele in zip(*stations.micapsdata.stations)]
            stations_array = zip(*stations.micapsdata.stations)
            # 画站点mark
            if m is not plt:
                stations_array[2], stations_array[1] = \
                    Micaps.UpdateXY(m, stations_array[2], stations_array[1])
            marker = MarkerStyle(stations.markstyle[0], stations.markstyle[1])
            m.scatter(stations_array[2],
                      stations_array[1],
                      marker=marker,
                      s=stations.radius,
                      c=stations.color,
                      alpha=stations.alpha,
                      edgecolors=stations.edgecolors)

            # 画站点文本

            fontfile = r"C:\WINDOWS\Fonts\{0}".format(stations.font[1])
            if not os.path.exists(fontfile):
                font = FontProperties(size=stations.font[0],
                                      weight=stations.font[2])
            else:
                font = FontProperties(fname=fontfile,
                                      size=stations.font[0],
                                      weight=stations.font[2])
            for sta in stations.micapsdata.stations:
                if m is not plt:
                    lon, lat = Micaps.UpdateXY(m, sta[2], sta[1])
                    lon1, lat1 = Micaps.UpdateXY(m, sta[2] + stations.detax,
                                                 sta[1])
                    deta = lon1 - lon
                else:
                    lon, lat = sta[2], sta[1]
                    deta = stations.detax
                plt.text(lon + deta,
                         lat,
                         sta[6],
                         fontproperties=font,
                         rotation=0,
                         color=stations.font[3],
                         ha='left',
                         va='center')

        # 接近收尾

        # self.Clip(clipborder, fig, patch)

        # 存图
        Picture.savePicture(fig, products.picture.picfile)

        print(products.picture.picfile + u'存图成功!')
        if debug:
            plt.show()
コード例 #30
0
ファイル: plotUtility.py プロジェクト: lina489/kilonovae
def asManyPlots(numPlot,
                datax,
                datay,
                hideXlabel=False,
                hideYlabel=False,
                hideYticks=False,
                placeYaxisOnRight=False,
                xlabel="",
                ylabel='',
                marker='o',
                color='black',
                plotFlag=True,
                label='',
                zorder=None,
                textsize=24,
                showLegend=False,
                legendTextSize=24,
                linestyle='None',
                ylim=[None, None],
                xlim=[None, None],
                cmap='Greys',
                cmapMin=None,
                cmapMax=None,
                showColorbar=False,
                locLegend='best',
                tickSize=24,
                title='',
                titlesize=24,
                colorbarOrientation='vertical',
                colorbarLabel=None,
                colorbarTicks=None,
                colorbarTicksLabels=None,
                colorbarLabelSize=24,
                colorbarTicksSize=24,
                colorbarTicksLabelsSize=24,
                outputName=None,
                overwrite=False,
                tightLayout=True,
                linewidth=3,
                fillstyle='full',
                unfilledFlag=False,
                alpha=1.0,
                noCheck=False,
                legendNcols=1,
                removeGrid=False,
                markerSize=16,
                legendMarkerFaceColor=None,
                legendMarkerEdgeColor=None,
                legendLineColor=None,
                norm=None,
                xscale=None,
                yscale=None):
    """
    Function which plots on a highly configurable subplot grid either with pyplot.plot or pyplot.scatter. A list of X and Y arrays can be given to have multiple plots on the same subplot.
    This function has been developed to be used with numpy arrays or list of numpy arrays (structured or not). Working with astropy tables or any other kind of data structure might or might not work depending on its complexity and behaviour. 
    
    Input
    -----
    alpha : float, list of floats
        indicates the transparency of the data points (1 is plain, 0 is invisible)
    cmap : matplotlib colormap
        the colormap to use for the scatter plot only
    cmapMin: float
        the minmum value for the colormap
    cmapMax: float
        the maximum value for the colormap
    color : list of strings/chars/RGBs/lists of values
        color for the data. For scatter plots, the values must be in numpy array format. For plots, it can either be a string, char or RGB value.
        WARNING: it is highly recommanded to give the color as a list. For instance, if plotting only one plot of black color, you should preferentially use ['black'] rather than 'black'. For, say one plot and one scatter plot, you have to use ['black', yourNumpyArray].
    colorbarLabel : string
        the name to be put next to the colorbar
    colorbarLabelSize : int
        size of the label next to the colorbar
    colorbarOrientation : 'vertical' or 'horizontal'
        specifies if the colorbar must be place on the right or on the bottom of the graph
    colorbarTicks : list of int/float
        specifies the values taken by the ticks which will be printed next to the colorbar
    colorbarTicksLabels : list of string
        specifies the labels associated to the chosen ticks values
    colorbarTicksLabelsSize : int
        size of the labels associated to the chosen ticks
    colorbarTicksSize : int
        size of the chosen ticks
    datax: numpy array, list of numpy arrays
        the x data
    datay : numpy array, list of numpy arrays 
        the y data
    fillstyle : string, list of strings
        which fillstyle use for the markers (see matplotlib fillstyles for more information)
    hideXlabel : boolean
        whether to hide the x label or not
    hideYlabel : boolean
        whether to hide the y label or not
    hideYticks : boolean
        whether to hide the y ticks or not
    label : string
        legend label for the data
    legendLineColor : list of strings/chars/RGBs
        the line color in the legend. If None, uses the plot color (for plots) and black (for scatter plots) as default.
    legendMarkerEdgeColor : list of strings/chars/RGBs
        the color of the edges of each marker in the legend. If None, uses the plot color (for plots) and black (for scatter plots) as default.
    legendMarkerFaceColor : list of strings/chars/RGBs
        the face color (color of the main area) of each marker in the legend. If None, uses the plot color (for plots) and black (for scatter plots) as default.
    legendNcols : int
        number of columns in the legend
    legendTextSize : int
        size for the legend
    linestyle : string, list of strings for many plots
        which line style to use
    linewidth : float
        the width of the line
    locLegend : string, int
        position where to place the legend
    marker : string, char, list of both for many plots
        the marker to use for the data
    markerSize : float or list of floats for scatter plots
        the size of the marker
    noCheck : boolean
        whether to check the given parameters all have the relevant shape or not
    norm : Matplotlib Normalize instance
        the norm of the colormap (for log scale colormaps for instance)
    numPlot : int (3 digits)
        the subplot number
    outputName : str
        name of the file to save the graph into. If None, the plot is not saved into a file
    overwrite : boolean
        whether to overwrite the ouput file or not
    placeYaxisOnRight : boolean
        whether to place the y axis of the plot on the right or not
    plotFlag : boolean, list of booleans for many plots
        if True, plots with pyplot.plot function. If False, use pyplot.scatter
    removeGrid : boolean, list of booleans for many plots
        whether to remove the grid or not
    textsize : int
        size for the labels
    showColorbar : boolean
        whether to show the colorbar for a scatter plot or not
    showLegend : boolean
        whether to show the legend or not
    tickSize : int
        size of the ticks on both axes
    tightLayout : boolean
        whether to use bbox_inches='tight' if tightLayout is True or bbox_inches=None otherwise
    unfilledFlag : boolean, list of booleans
        whether to unfill the points' markers or not
    xlabel : string
        the x label
    xlim : list of floats/None
        the x-axis limits to use. If None is specified as lower/upper/both limit(s), the minimum/maximum/both values are used
    xscale : string
        the scale to use (most used are "linear", "log", "symlog") for the x axis
    ylabel : string
        the y label
    ylim : list of floats/None
        the y-axis limits to use. If None is specified as lower/upper/both limit(s), the minimum/maximum/both values are used
    yscale : string
        the scale to use (most used are "linear", "log", "symlog") for the y axis
    zorder : int, list of ints for many plots
        whether the data will be plot in first position or in last. The lower the value, the earlier it will be plotted
        
    Return current axis and last plot.
    """

    try:
        len(numPlot)
        ax1 = plt.subplot(numPlot[0], numPlot[1], numPlot[2])
    except:
        ax1 = plt.subplot(numPlot)
    ax1.yaxis.set_ticks_position('both')
    ax1.xaxis.set_ticks_position('both')
    ax1.set_title(title, size=titlesize)
    ax1.tick_params(which='both', direction='in', labelsize=tickSize)

    if not removeGrid:
        plt.grid(zorder=1000)

    #Checking shape consistency between datax and datay
    shpX = np.shape(datax)
    shpY = np.shape(datay)
    if shpX != shpY:
        exit("X data was found to have shape", shpX,
             "but Y data seems to have shape", shpY, ".Exiting.")

    #If we have an array instead of a list of arrays, transform it to the latter
    try:
        np.shape(datax[0])[0]
    except:
        datax = [datax]
        datay = [datay]

    lx = len(datax)

    #If we have only one marker/color/zorder/linestyle/label/plotFlag, transform them to a list of the relevant length
    if not noCheck:
        try:
            np.shape(linestyle)[0]
        except:
            linestyle = [linestyle] * lx
    try:
        np.shape(marker)[0]
    except:
        marker = [marker] * lx
    try:
        np.shape(markerSize)[0]
    except:
        markerSize = [markerSize] * lx

    try:
        np.shape(legendMarkerFaceColor)[0]
    except:
        legendMarkerFaceColor = [legendMarkerFaceColor] * lx

    try:
        np.shape(legendMarkerEdgeColor)[0]
    except:
        legendMarkerEdgeColor = [legendMarkerEdgeColor] * lx

    try:
        np.shape(legendLineColor)[0]
    except:
        legendLineColor = [legendLineColor] * lx

    if len(color) == 1:
        color = [color] * lx

    if zorder is None:
        zorder = range(1, lx + 1)

    try:
        np.shape(plotFlag)[0]
    except:
        plotFlag = [plotFlag] * lx
    try:
        np.shape(fillstyle)[0]
    except:
        fillstyle = [fillstyle] * lx
    try:
        np.shape(unfilledFlag)[0]
    except:
        unfilledFlag = [unfilledFlag] * lx
    try:
        np.shape(alpha)[0]
    except:
        alpha = [alpha] * lx
    try:
        np.shape(label)[0]
    except:
        if lx > 1:
            if showLegend:
                print(
                    "Not enough labels were given compared to data dimension. Printing empty strings instead."
                )
            label = ''
        label = [label] * lx

#     print(color, marker, zorder, linestyle, plotFlag, label)

#hiding labels if required
    if hideXlabel:
        ax1.axes.get_xaxis().set_ticklabels([])
    else:
        plt.xlabel(xlabel, size=textsize)
    if hideYticks:
        ax1.axes.get_yaxis().set_ticklabels([])
    if not hideYlabel:
        plt.ylabel(ylabel, size=textsize)

    #Place Y axis on the right if required
    if placeYaxisOnRight:
        ax1.yaxis.tick_right()
        ax1.yaxis.set_label_position("right")

    #Plotting
    tmp = []
    sct = None

    #list of handels for the legend
    handles = []

    # Compute cmap minimum and maximum if there are any scatter plots (it is inefficient because color list contains lists and strings, so we cannot convert it easily into an array to use vectorized function)
    tmp = []
    for col, flag in zip(color, np.array(plotFlag) == False):
        if flag:
            tmp.append(col)
    if len(tmp) > 0:
        cmapMin = np.min(tmp)
        cmapMax = np.max(tmp)

    for dtx, dty, mrkr, mrkrSz, clr, zrdr, lnstl, lbl, pltFlg, fllstl, lph, nflldFlg in zip(
            datax, datay, marker, markerSize, color, zorder, linestyle, label,
            plotFlag, fillstyle, alpha, unfilledFlag):
        edgecolor = clr
        if nflldFlg:
            facecolor = "none"
        else:
            facecolor = clr

        if pltFlg:
            tmp.append(
                plt.plot(dtx,
                         dty,
                         label=lbl,
                         marker=mrkr,
                         color=clr,
                         zorder=zrdr,
                         alpha=lph,
                         linestyle=lnstl,
                         markerfacecolor=facecolor,
                         markeredgecolor=edgecolor,
                         markersize=mrkrSz,
                         linewidth=linewidth))
            handles.append(copy(tmp[-1][0]))
        else:
            print(clr, cmap)
            markerObject = MarkerStyle(marker=mrkr, fillstyle=fllstl)
            sct = plt.scatter(dtx,
                              dty,
                              label=lbl,
                              marker=markerObject,
                              zorder=zrdr,
                              cmap=cmap,
                              norm=norm,
                              vmin=cmapMin,
                              vmax=cmapMax,
                              alpha=lph,
                              c=clr,
                              s=mrkrSz)
            print(sct)
            tmp.append(sct)

            if nflldFlg:
                sct.set_facecolor('none')

    if np.any(np.logical_not(plotFlag)) and showColorbar:
        col = plt.colorbar(sct, orientation=colorbarOrientation)
        col.ax.tick_params(labelsize=colorbarTicksLabelsSize)

        if colorbarLabel is not None:
            col.set_label(colorbarLabel, size=colorbarLabelSize)
        if colorbarTicks is not None:
            col.set_ticks(colorbarTicks)
        if colorbarTicksLabels is not None:
            if colorbarOrientation == 'vertical':
                col.ax.set_yticklabels(colorbarTicksLabels,
                                       size=colorbarTicksLabelsSize)
            elif colorbarOrientation == 'horizontal':
                col.ax.set_xticklabels(colorbarTicksLabels,
                                       size=colorbarTicksLabelsSize)

    if showLegend:

        def isOrisNotNone(data, default):
            for num, i in enumerate(data):
                if i is None:
                    data[num] = default
            return data

        if pltFlg:
            for h, mkfclr, mkeclr, lc, c in zip(handles, legendMarkerFaceColor,
                                                legendMarkerEdgeColor,
                                                legendLineColor, color):
                mkfclr, mkeclr, lc = isOrisNotNone([mkfclr, mkeclr, lc], c)

                h.set_color(lc)
                h.set_markerfacecolor(mkfclr)
                h.set_markeredgecolor(mkeclr)
            leg = plt.legend(loc=locLegend,
                             prop={'size': legendTextSize},
                             shadow=True,
                             fancybox=True,
                             ncol=legendNcols,
                             handles=handles)

        if not pltFlg:
            leg = plt.legend(loc=locLegend,
                             prop={'size': legendTextSize},
                             shadow=True,
                             fancybox=True,
                             ncol=legendNcols)

            for marker, mkfclr, mkeclr, lc in zip(leg.legendHandles,
                                                  legendMarkerFaceColor,
                                                  legendMarkerEdgeColor,
                                                  legendLineColor):
                mkfclr = isOrisNotNone([mkfclr], 'black')

                marker.set_color(mkfclr)

    if yscale is not None:
        plt.yscale(yscale)
    if xscale is not None:
        plt.xscale(xscale)

    #Define Y limits if required
    if ylim[0] is not None:
        ax1.set_ylim(bottom=ylim[0])
#     else:
#         ax1.set_ylim(bottom=ax.get_ylim()[0])
    if ylim[1] is not None:
        ax1.set_ylim(top=ylim[1])
#    else:
#         ax1.set_ylim(top=ax1.get_ylim()[1])

#define X limits if required
    if xlim[0] is not None:
        ax1.set_xlim(left=xlim[0])
#     else:
#         ax1.set_xlim(left=ax.get_xlim()[0])
    if xlim[1] is not None:
        ax1.set_xlim(right=xlim[1])


#     else:
#         ax1.set_xlim(right=ax.get_xlim()[1])

    if outputName is not None:
        #If we do not want to overwrite the file
        f = None
        if not overwrite:
            #Try to open it to check if it exists
            try:
                f = open(outputName, 'r')
            except:
                pass
            if f is not None:
                print(
                    'File %s already exists but overwritting was disabled. Thus exiting without writing.'
                    % outputName)
                return ax1, tmp

        f = open(outputName, 'w')

        bbox_inches = None
        if tightLayout:
            bbox_inches = 'tight'

        plt.savefig(outputName, bbox_inches=bbox_inches)

    return ax1, tmp