Beispiel #1
0
    def __init__(self, bbox, **kwargs):
        if "transform" in kwargs:
            raise ValueError("transform should not be set")

        kwargs["transform"] = IdentityTransform()
        Patch.__init__(self, **kwargs)
        self.bbox = bbox
Beispiel #2
0
    def set_3d_properties(self, verts, zs=0, zdir='z'):
        if not iterable(zs):
            zs = np.ones(len(verts)) * zs

        self._segment3d = [juggle_axes(x, y, z, zdir) \
                for ((x, y), z) in zip(verts, zs)]
        self._facecolor3d = Patch.get_facecolor(self)
Beispiel #3
0
 def __init__(self, bbox1, bbox2, loc1, loc2=None, **kwargs):
     """
     *path* is a :class:`matplotlib.path.Path` object.
     Valid kwargs are:
     %(Patch)s
     .. seealso::
         :class:`Patch`
             For additional kwargs
     """
     if "transform" in kwargs:
        raise ValueError("trnasform should nt be set")
     kwargs["transform"] = IdentityTransform()
     Patch.__init__(self, **kwargs)
     self.bbox1 = bbox1
     self.bbox2 = bbox2
     self.loc1 = loc1
     self.loc2 = loc2
Beispiel #4
0
    def __init__(self, bbox1, bbox2, loc1, loc2=None, **kwargs):
        """
        Connect two bboxes with a straight line.

        Parameters
        ----------
        bbox1, bbox2 : `matplotlib.transforms.Bbox`
            Bounding boxes to connect.

        loc1 : {1, 2, 3, 4}
            Corner of *bbox1* to draw the line. Valid values are::

                'upper right'  : 1,
                'upper left'   : 2,
                'lower left'   : 3,
                'lower right'  : 4

        loc2 : {1, 2, 3, 4}, optional
            Corner of *bbox2* to draw the line. If None, defaults to *loc1*.
            Valid values are::

                'upper right'  : 1,
                'upper left'   : 2,
                'lower left'   : 3,
                'lower right'  : 4

        **kwargs
            Patch properties for the line drawn. Valid arguments include:

            %(Patch)s
        """
        if "transform" in kwargs:
            raise ValueError("transform should not be set")

        kwargs["transform"] = IdentityTransform()
        if 'fill' in kwargs:
            Patch.__init__(self, **kwargs)
        else:
            fill = bool({'fc', 'facecolor', 'color'}.intersection(kwargs))
            Patch.__init__(self, fill=fill, **kwargs)
        self.bbox1 = bbox1
        self.bbox2 = bbox2
        self.loc1 = loc1
        self.loc2 = loc2
    def __init__(self, bbox, **kwargs):
        """
        Patch showing the shape bounded by a Bbox.

        Parameters
        ----------
        bbox : `matplotlib.transforms.Bbox`
            Bbox to use for the extents of this patch.

        **kwargs
            Patch properties. Valid arguments include:
            %(Patch)s
        """
        if "transform" in kwargs:
            raise ValueError("transform should not be set")

        kwargs["transform"] = IdentityTransform()
        Patch.__init__(self, **kwargs)
        self.bbox = bbox
 def __init__(self, xy, radius, **kwargs):
     """
     xy : array_like
       center of two circles
     radius : scalar
       size of each circle
       
     Valid kwargs are:
     %(Patch)s
     """
     Patch.__init__(self, **kwargs)
     self.center = xy
     self.radius = radius
     self.width = 4. # two x unit circle (i.e. from +1 to -1)
     self.height = 2. # one x unit circle
     path = copy(Path.unit_circle())
     n_pts = path.vertices.shape[0]
     path.vertices = np.tile(path.vertices, [2,1])
     path.vertices[:n_pts,0] -= 1
     path.vertices[n_pts:,0] += 1
     path.codes = np.tile(path.codes, [2])
     self._path = path
     # Note: This cannot be calculated until this is added to an Axes
     self._patch_transform = transforms.IdentityTransform()
Beispiel #7
0
###############################################################################
# In this case, the cross-validation retained the same ratio of classes across
# each CV split. Next we'll visualize this behavior for a number of CV
# iterators.
#
# Visualize cross-validation indices for many CV objects
# ------------------------------------------------------
#
# Let's visually compare the cross validation behavior for many
# scikit-learn cross-validation objects. Below we will loop through several
# common cross-validation objects, visualizing the behavior of each.
#
# Note how some use the group/class information while others do not.

cvs = [KFold, GroupKFold, ShuffleSplit, StratifiedKFold,
       GroupShuffleSplit, StratifiedShuffleSplit, TimeSeriesSplit]


for cv in cvs:
    this_cv = cv(n_splits=n_splits)
    fig, ax = plt.subplots(figsize=(6, 3))
    plot_cv_indices(this_cv, X, y, groups, ax, n_splits)

    ax.legend([Patch(color=cmap_cv(.8)), Patch(color=cmap_cv(.02))],
              ['Testing set', 'Training set'], loc=(1.02, .8))
    # Make the legend fit
    plt.tight_layout()
    fig.subplots_adjust(right=.7)
plt.show()
def plot_read_counts(labels,
                     counts,
                     labels_on_flowcell,
                     labels_in_run,
                     possible_labels=None,
                     ax=None,
                     vmax=None,
                     title_note=None):
    from matplotlib.patches import Patch
    if vmax is None:
        vmax = max(counts) + max(int(0.1 * max(counts)), 100)
    if ax == None:
        fig, ax = plt.subplots(figsize=(30, 8))
    if possible_labels is None:
        possible_labels = labels[:]
    g = sns.barplot(x=labels, y=counts, order=possible_labels, ax=ax)
    title = "#/reads identified per barcode"
    if title_note is not None:
        title += "\n(%s)" % title_note
    ax.set_title(title)
    ax.set_xlabel("Barcode ID")
    ax.set_ylabel("Read counts")
    ax.set_ylim([0, vmax])

    prev_text_height = 0
    for j, label in enumerate(possible_labels):
        if label in labels:
            count = counts[labels.index(label)]
        else:
            count = 0
        if label == "-1":
            continue

        if label in labels_in_run:
            g.containers[0].get_children()[j].set_facecolor("tab:red")
            font_kwargs = {"color": "tab:red", "weight": "bold"}
        elif label in labels_on_flowcell:
            g.containers[0].get_children()[j].set_facecolor("tab:blue")
            font_kwargs = {"color": "k", "weight": "bold"}
        else:
            g.containers[0].get_children()[j].set_facecolor("k")
            font_kwargs = {"color": "k", "weight": "normal"}

        diff = prev_text_height - (count + 0.01 * vmax)
        if count < 100:
            text_height = count + .01 * vmax
            ax.text(j, text_height, count, ha="center", **font_kwargs)
        elif diff < 0 and np.abs(diff) < vmax * .06:
            text_height = np.max(
                [prev_text_height + .035 * vmax, count + .01 * vmax])
            ax.text(j, text_height, count, ha="center", **font_kwargs)
        elif np.abs(diff) < vmax * .05:
            text_height = np.min(
                [prev_text_height - .01 * vmax, count + .01 * vmax])
            ax.text(j, text_height, count, ha="center", **font_kwargs)
        else:
            text_height = count + .01 * vmax
            ax.text(j, text_height, count, ha="center", **font_kwargs)
        prev_text_height = text_height

    legend_elements = [
        Patch(facecolor='k',
              edgecolor='k',
              label='never been run on this flowcell'),
        Patch(facecolor='tab:blue',
              edgecolor='tab:blue',
              label='prev run on flowcell'),
        Patch(facecolor='tab:red',
              edgecolor='tab:red',
              label='current run on flowcell')
    ]
    leg = ax.legend(handles=legend_elements)
    t1, t2, t3 = leg.get_texts()
    t2._fontproperties = t1._fontproperties.copy()
    t3._fontproperties = t1._fontproperties.copy()
    t2.set_weight('bold')
    t3.set_weight('bold')
    t3.set_color("tab:red")
    return ax
Beispiel #9
0
              sigma=1.5,
              learning_rate=0.5,
              random_seed=1)

# Inicializando os pesos e treinando o SOM, usando 5000 epocas
som.pca_weights_init(X)
som.train_random(X, 5000, verbose=True)

# Retorna o mapa de neurônios associado a cada paiz
country_map = som.labels_map(X, democracy_index.country)

# Plotando o mapa da democracia
plt.figure(figsize=(10, 10))
for p, countries in country_map.items():
    countries = list(countries)
    x = p[0] + .1
    y = p[1] - .3
    for i, c in enumerate(countries):
        off_set = (i + 1) / len(countries) - 0.05
        plt.text(x, y + off_set, c, color=colors_dict[c], fontsize=8)
plt.pcolor(som.distance_map().T, cmap='gray_r', alpha=.8)
plt.xticks(np.arange(size + 1))
plt.yticks(np.arange(size + 1))
plt.grid()

legend_elements = [
    Patch(facecolor=clr, edgecolor='w', label=l)
    for l, clr in category_color.items()
]
plt.legend(handles=legend_elements, loc='center left', bbox_to_anchor=(1, .95))
plt.savefig('democracy.png')
Beispiel #10
0
def plot1(ctx):
    """Do main plotting logic"""
    df = read_sql(
        "SELECT * from sm_hourly WHERE "
        "station = %s and valid BETWEEN %s and %s ORDER by valid ASC",
        ctx["pgconn"],
        params=(ctx["station"], ctx["sts"], ctx["ets"]),
        index_col="valid",
    )
    if df.empty:
        raise NoDataFound("No Data Found for This Plot.")
    slrkw = df["slrkw_avg_qc"]
    d12sm = df["calc_vwc_12_avg_qc"]
    d12t = df["t12_c_avg_qc"]
    d24t = df["t24_c_avg_qc"]
    d50t = df["t50_c_avg_qc"]
    d24sm = df["calc_vwc_24_avg_qc"]
    d50sm = df["calc_vwc_50_avg_qc"]
    rain = df["rain_mm_tot_qc"]
    tair = df["tair_c_avg_qc"]
    tsoil = df["tsoil_c_avg_qc"]
    valid = df.index

    (fig, ax) = plt.subplots(3, 1, sharex=True, figsize=(8, 8))
    ax[0].grid(True)
    ax2 = ax[0].twinx()
    ax[0].set_zorder(ax2.get_zorder() + 1)
    ax[0].patch.set_visible(False)
    # arange leads to funky values
    ax2.set_yticks([-0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0])
    ax2.set_yticklabels([0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0])
    ax2.set_ylim(-0.6, 0)
    ax2.set_ylabel("Hourly Precipitation [inch]")
    ax2.bar(valid, 0 - rain / 25.4, width=0.04, fc="b", ec="b", zorder=4)

    if not d12sm.isnull().all():
        ax[0].plot(valid, d12sm * 100.0, linewidth=2, color="r", zorder=5)
    if not d24sm.isnull().all():
        ax[0].plot(valid, d24sm * 100.0, linewidth=2, color="purple", zorder=5)
    if not d50sm.isnull().all():
        ax[0].plot(valid, d50sm * 100.0, linewidth=2, color="black", zorder=5)
    ax[0].set_ylabel("Volumetric Soil Water Content [%]", fontsize=10)

    ax[0].set_title(("ISUSM Station: %s Timeseries") %
                    (ctx["_nt"].sts[ctx["station"]]["name"], ))
    box = ax[0].get_position()
    ax[0].set_position(
        [box.x0, box.y0 + box.height * 0.05, box.width, box.height * 0.95])
    box = ax2.get_position()
    ax2.set_position(
        [box.x0, box.y0 + box.height * 0.05, box.width, box.height * 0.95])
    handles = [
        Line2D([0], [0], color="r", lw=3, label="12 inch"),
        Line2D([0], [0], color="purple", lw=3, label="24 inch"),
        Line2D([0], [0], color="black", lw=3, label="50 inch"),
        Patch(facecolor="b", edgecolor="b", label="Hourly Precip"),
    ]
    ax[0].legend(
        handles=handles,
        bbox_to_anchor=(0.5, -0.15),
        ncol=4,
        loc="center",
        fontsize=12,
    )

    # ----------------------------------------
    if not d12t.isnull().all():
        ax[1].plot(
            valid,
            temperature(d12t, "C").value("F"),
            linewidth=2,
            color="r",
            label="12in",
        )
    if not d24t.isnull().all():
        ax[1].plot(
            valid,
            temperature(d24t, "C").value("F"),
            linewidth=2,
            color="purple",
            label="24in",
        )
    if not d50t.isnull().all():
        ax[1].plot(
            valid,
            temperature(d50t, "C").value("F"),
            linewidth=2,
            color="black",
            label="50in",
        )
    ax[1].grid(True)
    ax[1].set_ylabel(r"Soil Temperature $^\circ$F")
    box = ax[1].get_position()
    ax[1].set_position(
        [box.x0, box.y0 + box.height * 0.05, box.width, box.height * 0.95])

    # ------------------------------------------------------

    ax2 = ax[2].twinx()
    l3, = ax2.plot(valid, slrkw * 1000.0, color="g", zorder=1, lw=2)
    ax2.set_ylabel("Solar Radiation [W/m^2]", color="g")

    l1, = ax[2].plot(
        valid,
        temperature(tair, "C").value("F"),
        linewidth=2,
        color="blue",
        zorder=2,
    )
    l2, = ax[2].plot(
        valid,
        temperature(tsoil, "C").value("F"),
        linewidth=2,
        color="brown",
        zorder=2,
    )
    ax[2].grid(True)
    ax[2].legend(
        [l1, l2, l3],
        ["Air", '4" Soil', "Solar Radiation"],
        bbox_to_anchor=(0.5, 1.1),
        loc="center",
        ncol=3,
    )
    ax[2].set_ylabel(r"Temperature $^\circ$F")

    ax[2].set_zorder(ax2.get_zorder() + 1)
    ax[2].patch.set_visible(False)
    ax[0].set_xlim(df.index.min(), df.index.max())

    days = (ctx["ets"] - ctx["sts"]).days
    if days >= 3:
        interval = max(int(days / 7), 1)
        ax[2].xaxis.set_major_locator(
            mdates.DayLocator(interval=interval,
                              tz=pytz.timezone("America/Chicago")))
        ax[2].xaxis.set_major_formatter(
            mdates.DateFormatter("%-d %b\n%Y",
                                 tz=pytz.timezone("America/Chicago")))
    else:
        ax[2].xaxis.set_major_locator(
            mdates.AutoDateLocator(maxticks=10,
                                   tz=pytz.timezone("America/Chicago")))
        ax[2].xaxis.set_major_formatter(
            mdates.DateFormatter("%-I %p\n%d %b",
                                 tz=pytz.timezone("America/Chicago")))

    return fig, df
Beispiel #11
0
def generate():
    if not os.path.isdir(FLAGS.output_dir):
        os.mkdir(FLAGS.output_dir)

    train_writers = []
    for ii in range(FLAGS.num_files):
        train_writers.append(None if FLAGS.debug else \
                tf.python_io.TFRecordWriter(FLAGS.output_dir + "train_data%d.tfrecord" % ii))
    val_writer = None if FLAGS.debug else \
            tf.python_io.TFRecordWriter(FLAGS.output_dir + "validation_data.tfrecord")

    car_id = 26

    im_list, lab_list = writeFileList(FLAGS.cityscapes_root)

    count = 1
    for i in range(len(im_list)):
        im_fl = im_list[i]
        lab_fl = lab_list[i]

        print("Working on sample %d" % i)

        image = central_crop(cv2.imread(im_fl), vw, vh)
        lab = central_crop(
            cv2.imread(lab_fl, cv2.IMREAD_GRAYSCALE)[..., np.newaxis], vw, vh)

        mask_label = np.zeros((vh, vw, 2), dtype=np.bool)
        mask_label[:, :, 1:2] = lab == car_id
        if np.any(mask_label[:, :, 1]):
            mask_label[:, :, 0] = np.logical_not(mask_label[:, :, 1])
            if FLAGS.debug:
                mask = np.argmax(mask_label, axis=-1)
                rgb = np.zeros((vh, vw, 3))

                legend = []
                np.random.seed(0)
                for i in range(2):
                    c = np.random.rand(3)
                    case = mask == i
                    if np.any(case):
                        legend.append(
                            Patch(facecolor=tuple(c),
                                  edgecolor=tuple(c),
                                  label='background' if i == 0 else 'car'))

                    rgb[case, :] = c

                _image = cv2.resize(image, (vw, vh)) / 255.0

                _image = 0.3 * _image + 0.7 * rgb

                global imdata
                if imdata is None:
                    imdata = plt.imshow(_image)
                    f = plt.gca()
                    f.axes.get_xaxis().set_ticks([])
                    f.axes.get_yaxis().set_ticks([])
                else:
                    imdata.set_data(_image)

                lgd = plt.legend(handles=legend,
                                 loc='upper left',
                                 bbox_to_anchor=(1.0, 1))

                plt.pause(1e-9)
                plt.draw()
                plt.pause(3)

            else:
                features_ = {
                    'img':
                    bytes_feature(tf.compat.as_bytes(image.tostring())),
                    'label':
                    bytes_feature(
                        tf.compat.as_bytes(
                            mask_label.astype(np.uint8).tostring()))
                }
                example = tf.train.Example(features=tf.train.Features(
                    feature=features_))

                if 'val' in im_fl:
                    val_writer.write(example.SerializeToString())
                else:
                    train_writers[np.random.randint(0, FLAGS.num_files)].write(
                        example.SerializeToString())
            count += 1
        else:
            print("No cars. Skipping")
 def set_3d_properties(self, verts, zs=0, zdir='z'):
     zs = _backports.broadcast_to(zs, len(verts))
     self._segment3d = [
         juggle_axes(x, y, z, zdir) for ((x, y), z) in zip(verts, zs)
     ]
     self._facecolor3d = Patch.get_facecolor(self)
## the last second of the month.

idx = pd.date_range(start_date[month_index],
                    end_date[month_index],
                    freq='100ms')

df = df.set_index('Time').rename_axis(None)
df = df.reindex(idx, fill_value=np.nan)

# Plot a 'quality plot' with the jumps, fluctuations and dead zones

fig, ax = plt.subplots(1, 1, figsize=(12, 3))
ax.plot(df['Frequency'].values, color='black')

from matplotlib.patches import Patch
patch_l = Patch(color='gray',
                label='Quality of data (impossible to determine)')
fig.text(0.09, 0.8, r'Decimals = 0', fontsize=16)
ax.set_ylim([-550, 650])
ax.set_yticks([-400, -200, 0, 200, 400])
ax.set_xlabel('Time', fontsize=18)
ax.set_ylabel('F [mHz]', fontsize=18)
ax.legend(handles=[patch_l], loc=4, ncol=4, fontsize=14)
fig.subplots_adjust(left=0.07, bottom=0.18, right=.99, top=0.99)
fig.savefig(save_to + year + '_' + month + '.png', dpi=400, transparent=True)

# %% Save data into a zipped csv. location is save_to
df.to_csv(save_to + 'finland_' + year + '_' + month + '.csv.zip',
          float_format='%.0f',
          compression=dict(method='zip',
                           archive_name=year + '_' + month + '.csv'))
Beispiel #14
0
def plot(
    self,
    fig=None,
    ax=None,
    is_lam_only=False,
    sym=1,
    alpha=0,
    delta=0,
    is_edge_only=False,
    is_display=True,
    is_show_fig=True,
):
    """Plot the Lamination in a matplotlib fig

    Parameters
    ----------
    self : LamSlotMulti
        A LamSlotMulti object
    fig : Matplotlib.figure.Figure
        existing figure to use if None create a new one
    ax : Matplotlib.axes.Axes object
        Axis on which to plot the data
    is_lam_only: bool
        True to plot only the lamination
    sym : int
        Symmetry factor (1= full machine, 2= half of the machine...)
    alpha : float
        Angle for rotation [rad]
    delta : complex
        Complex value for translation
    is_edge_only: bool
        To plot transparent Patches
    is_display : bool
        False to return the patches
    is_show_fig : bool
        To call show at the end of the method
    Returns
    -------
    patches : list
        List of Patches
    """

    if self.is_stator:
        lam_color = STATOR_COLOR
    else:
        lam_color = ROTOR_COLOR

    (fig, axes, patch_leg, label_leg) = init_fig(fig=fig, ax=ax, shape="rectangle")

    surf_list = self.build_geometry(sym=sym, alpha=alpha, delta=delta)
    patches = list()
    for surf in surf_list:
        if "Ext" in surf.label:
            patches.extend(surf.get_patches(color=lam_color, is_edge_only=is_edge_only))
        else:
            patches.extend(surf.get_patches(is_edge_only=is_edge_only))
    # Display the result
    if is_display:
        (fig, axes, patch_leg, label_leg) = init_fig(fig)
        axes.set_xlabel("(m)")
        axes.set_ylabel("(m)")
        for patch in patches:
            axes.add_patch(patch)

        # Axis Setup
        axis("equal")

        # The Lamination is centered in the figure
        Lim = self.Rext * 1.5
        axes.set_xlim(-Lim, Lim)
        axes.set_ylim(-Lim, Lim)

        # Add the legend
        if not is_edge_only:
            if self.is_stator:
                patch_leg.append(Patch(color=STATOR_COLOR))
                label_leg.append("Stator")
                axes.set_title("Stator with empty slot")
            else:
                patch_leg.append(Patch(color=ROTOR_COLOR))
                label_leg.append("Rotor")
                axes.set_title("Rotor with empty slot")

            legend(patch_leg, label_leg)
        if is_show_fig:
            fig.show()
    else:
        return patches
    def draw(self, X, y=None, **kwargs):
        """
        Called from the fit method, this method creates a decision boundary
        plot, and if self.scatter is True, it will scatter plot that draws
        each instance as a class or target colored point, whose location
        is determined by the feature data set.
        """
        # ensure that if someone is passing in another X such as X_test, that
        # features will be properly handled
        X = self._select_feature_columns(X)

        color_cycle = iter(
            resolve_colors(colors=self.colors, n_colors=len(self.classes_)))
        colors = OrderedDict([(c, next(color_cycle))
                              for c in self.classes_.keys()])

        self.ax.pcolormesh(
            self.xx,
            self.yy,
            self.Z_shape,
            alpha=self.pcolormesh_alpha,
            cmap=ListedColormap(colors.values()))

        # Create a data structure to hold the scatter plot representations
        to_plot = OrderedDict()
        for index in self.classes_.values():
            to_plot[index] = [[], []]

        # Add each row of the data set to to_plot for plotting
        for i, row in enumerate(X):
            row_ = np.repeat(np.expand_dims(row, axis=1), 2, axis=1)
            x_, y_ = row_[0], row_[1]
            # look up the y class name if given in init
            if self.class_labels is not None:
                target = self.class_labels[y[i]]
            else:
                target = y[i]
            index = self.classes_[target]
            to_plot[index][0].append(x_)
            to_plot[index][1].append(y_)

        # Add the scatter plots from the to_plot function
        # TODO: store these plots to add more instances to later
        # TODO: make this a separate function

        if self.show_scatter:
            for kls, index in self.classes_.items():
                self.ax.scatter(
                    to_plot[index][0],
                    to_plot[index][1],
                    marker=next(self.markers),
                    color=colors[kls],
                    alpha=self.scatter_alpha,
                    s=30,
                    edgecolors='black',
                    label=str(kls),
                    **kwargs)
        else:
            labels = [
                Patch(color=colors[kls], label=kls)
                for kls in self.classes_.keys()
            ]
            self.ax.legend(handles=labels)
# flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
flatui = ["#9b59b6", "#3498db", "#e74c3c", "#34495e", "#2ecc71"]
flatui = flatui[:len(cost_labels)]
sns.set_palette(sns.color_palette(flatui))
my_cmap = ListedColormap(sns.color_palette(flatui).as_hex())
# ax2.stackplot(iteration_index[1:], all_costs, labels=cost_labels)
# plt.yscale('log')
df_perc = df.divide(df.sum(axis=1), axis=0) * 100
df_perc.plot.area(ax=ax2, stacked=True, cmap=my_cmap,
                  linewidth=0.1)  # , colors=)
# df.plot(ax=ax2)
# plt.yscale('log')
ax2.set_ylabel('Contribution to cost (%)')
ax2.set_xlabel('Iteration #')
legend_elements = [Patch(facecolor=flatui[len(cost_labels) - 1], edgecolor='k',
                         label=cost_labels[-1])] \
                  + [Patch(facecolor=flatui[i], edgecolor='k',
                           label=cost_labels[i])
                     for i in range(0, len(cost_labels) - 1)]
ax2.legend(handles=legend_elements,
           fancybox=False,
           frameon=True,
           loc='center right')  # , loc='upper
# center',
# ncol=len(df.columns))
ax2.xaxis.set_ticks_position('both')
ax2.yaxis.set_ticks_position('both')
ax2.tick_params(labeltop=False,
                labelbottom=True,
                labelleft=True,
                labelright=True)
 def __init__(self, path, **kwargs):
     zs = kwargs.pop('zs', [])
     zdir = kwargs.pop('zdir', 'z')
     Patch.__init__(self, **kwargs)
     self.set_3d_properties(path, zs, zdir)
 def draw(self, renderer):
     Patch.draw(self, renderer)
Beispiel #19
0
 def set_3d_properties(self, verts, zs=0, zdir='z'):
     zs = np.broadcast_to(zs, len(verts))
     self._segment3d = [juggle_axes(x, y, z, zdir)
                        for ((x, y), z) in zip(verts, zs)]
     self._facecolor3d = Patch.get_facecolor(self)
Beispiel #20
0
 def __init__(self, path, *, zs=(), zdir='z', **kwargs):
     Patch.__init__(self, **kwargs)
     self.set_3d_properties(path, zs, zdir)
Beispiel #21
0
    def plot_frequency_map(cls,
                           geo_data,
                           admin_id_column,
                           frequencies,
                           labels=None,
                           label_position_columns=None,
                           callout_position_columns=None,
                           show_legend=True,
                           ax=None):
        """
        Plots a map of the given geo data with a choropleth showing the frequency of responses in each administrative
        region.

        The map is plotted to the specified axes or to the active matplotlib figure.
        Use matplotlib.pyplot to access and manipulate the result.

        :param geo_data: GeoData to plot.
        :type geo_data: geopandas.GeoDataFrame
        :param admin_id_column: Column in `geo_data` of the administrative region ids.
        :type admin_id_column: str
        :param frequencies: Dictionary of admin_id -> frequency.
        :type frequencies: dict of str -> int
        :param labels: Dictionary of admin_id -> text to annotate the map with for each administrative region.
        :type labels: dict of str -> str
        :param label_position_columns: A tuple specifying which columns in the `geo_data` contain the positions to draw
                                       each frequency label at, or None.
                                       The format is (X Position Column, Y Position Column). Positions should be in
                                       the same coordinate system as the geometry, and represent the vertical and
                                       horizontal center position of the drawn label.
                                       If None, no frequency labels are drawn.
        :type label_position_columns: (str, str) | None
        :param callout_position_columns: A tuple specifying which columns in the `geo_data` contain the positions to
                                         draw callout lines to, or None.
                                         The format is (X Position Column, Y Position Column). Positions should be in
                                         the same coordinate system as the geometry, and represent the target location
                                         to draw the callout line to. The callout line is drawn from the label_position
                                         for this feature.
                                         If None, no callout lines are drawn.
        :type callout_position_columns: (str, str) | None
        :param show_legend: Whether to draw a legend for the choropleth. The legend will be drawn to the bottom-right
                            corner.
        :type show_legend: bool
        :param ax: Axes on which to draw the plot. If None, draws to a new figure.
        :type ax: matplotlib.pyplot.Axes | None
        """
        # Class the frequencies using the Fisher-Jenks method, a standard GIS algorithm for choropleth classification.
        # Using this method prevents a region with a vastly higher frequency than the others (e.g. a capital city)
        # from using up all of the colour range, as would happen with a linear scale.
        # Ignores zeros when classing, so that 0s are not included in the same class as other lower numbers, then adds
        # the 0 back in when converting from classes to bin edges.
        frequencies_to_class = [f for f in frequencies.values() if f != 0]
        number_of_classes = min(5, len(set(frequencies_to_class)))
        bin_edges = [0]
        if number_of_classes > 0:
            bin_edges.extend(
                FisherJenks(np.array(frequencies_to_class),
                            k=number_of_classes).bins)

        # Get the color for each region by searching for the appropriate bin for each frequency.
        colors = []
        for i, admin_region in geo_data.iterrows():
            frequency = frequencies[admin_region[admin_id_column]]
            bin_id = [i for i, b in enumerate(bin_edges) if b >= frequency
                      ][0]  # Index of first bin edge >= frequency
            colors.append(
                cls.AVF_COLOR_MAP(0 if bin_id == 0 else float(bin_id) /
                                  number_of_classes))

        # Plot the choropleth map.
        ax = geo_data.plot(ax=ax,
                           color=colors,
                           linewidth=0.1,
                           edgecolor="black")
        ax.axis("off")

        # Add the choropleth legend.
        if show_legend:
            legend_elements = [
                Patch(label="0",
                      facecolor=cls.AVF_COLOR_MAP(0),
                      linewidth=0.1,
                      edgecolor="black")
            ]
            for bin_id in range(1, len(bin_edges)):
                range_min = bin_edges[bin_id - 1] + 1
                range_max = bin_edges[bin_id]
                legend_elements.append(
                    Patch(label=range_min if range_min == range_max else
                          f"{range_min} - {range_max}",
                          facecolor=cls.AVF_COLOR_MAP(
                              float(bin_id) / number_of_classes),
                          linewidth=0.1,
                          edgecolor="black"))
            ax.legend(handles=legend_elements,
                      title="Participants",
                      title_fontsize=6,
                      loc="lower right",
                      frameon=False,
                      handlelength=1.8,
                      handleheight=1.8,
                      labelspacing=0,
                      prop=dict(size=5.5))

        # Add a label to each administrative region showing its absolute frequency.
        # The font size is currently hard-coded for Kenyan counties.
        # TODO: Modify once per-map configuration needs are better understood by testing on other maps.
        if labels is not None:
            for i, admin_region in geo_data.iterrows():
                # Set label and callout positions from the features in the geo_data,
                # translating from the geo_data format to the matplotlib format.
                if callout_position_columns is None or pandas.isna(
                        admin_region[callout_position_columns[0]]):
                    # Draw label only.
                    xy = (admin_region[label_position_columns[0]],
                          admin_region[label_position_columns[1]])
                    xytext = None
                else:
                    # Draw label and callout line.
                    xy = (admin_region[callout_position_columns[0]],
                          admin_region[callout_position_columns[1]])
                    xytext = (admin_region[label_position_columns[0]],
                              admin_region[label_position_columns[1]])

                ax.annotate(text=labels[admin_region[admin_id_column]],
                            xy=xy,
                            xytext=xytext,
                            arrowprops=dict(facecolor="black",
                                            arrowstyle="-",
                                            linewidth=0.1,
                                            shrinkA=0,
                                            shrinkB=0),
                            ha="center",
                            va="center",
                            fontsize=3.8)
Beispiel #22
0
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

# settings
sns.set_style("ticks")
rcParams['font.family'] = 'serif'
pal = {
    'theoretical': '#000000',
    'simulated': '#597DBE',
    'fasttree': '#FF9980',
    'raxml': '#A2B7C3'
}
handles = [
    Patch(color=pal['theoretical'], label='Theoretical'),
    Patch(color=pal['simulated'], label='Simulated'),
    Patch(color=pal['fasttree'], label='FastTree'),
    Patch(color=pal['raxml'], label='RAxML')
]
axisY = np.asarray([i / 10.0 for i in range(0, 5)])


# Expected Number of Cherries as a Function of r
def cherries_vs_r(r):
    return (r**0.5) / (1 + r + r**0.5)


# DATASETS
# modifying r = lambdaA/lambdaB (with different lambda = lambdaA+lambdaB to keep expected branch length constant)
r_original = {
Beispiel #23
0
def distplot_log_reg_from_csv(ind_var1: str, ind_var2: str, dep_vars: list,
                              sample_size: int, repeat: int, log_reg_date: str,
                              bootstrap_id: int, max_model_size: int,
                              max_expr_len: int, language_name: str,
                              lang_gen_date: int):
    '''Make and store distplots of existing logistic regression results.

    Plot coefficient distributions of regression over language data.
    For each property in dep_vars, make distplot of coefficient 
    distribution of raw score and randomly shuffled score.
    Below that, plot distribution of the difference in coefficient
    for raw scores and randomly shuffled scores.

    Args: 
        ind_var1: A string. Should be f"{score}zscore", i.e. zscore of
            raw score, for score in {"ml", "lz"}.
        ind_var1: A string. Should be f"{score}_shuff_zscore", i.e. 
            zscore of randomly shuffled score, for score in 
            {"ml", "lz"}.
        dep_vars: A list of strings. The names of the quantifier props:
            the dependent variables. For each there wil be a distplot.
        sample_size: An int. The size of the data samples that were used
            for the regressions.
        repeat: An int. The number of samples that were taken, 
            i.e. the number regressions.
        log_reg_date: A string. The date on which the regression data
            was made.
        bootstrap_id: An int. Used for loading csv data with logistic
            regression data. Identifies the bootstrap series for a given
            date. Multiple regression sessions were done on the same data 
            to check for convergence.
        max_model_size: An int. Used for loading and storing csv data.
            The maximum model size over which the meaning of quantifiers
            was computed in the language data.
        max_expr_len: An int. Used for loading and storing csv data.
            The maximum expression length of the quantifiers expressions
            in the language data.
        language_name: A string. Used for loading and storing csv data.
            Identifies the the collection of operators used for 
            generating the language data.
        lang_gen_date: A string. Used for loading and storing csv data.
            The date on which the language data was generated.
        print_summary: True or False. Print the regression summary of
            each sample when True. Reports on convergence.
        verbose: True or False. Print the regression results when True.

    '''
    dep_vars_names = {
        "mon_cons": "Both",
        "mon_quan_cons": "All",
        "monotonicity": "Monotonicity",
        "quantity": "Quantity",
        "conservativity": "Conservativity"
    }
    csv_fileloc = utils.make_log_reg_csv_path(max_model_size, language_name,
                                              lang_gen_date, log_reg_date)
    if len(dep_vars) == 4:
        costum_figsize = (10, 5)
    if len(dep_vars) == 3:
        costum_figsize = (7.5, 5)
    fig, axs = plt.subplots(2,
                            len(dep_vars),
                            constrained_layout=True,
                            figsize=costum_figsize)
    for ax in range(len(dep_vars)):
        csv_filename = utils.make_log_reg_csv_filename(
            ind_var1, dep_vars[ax], bootstrap_id, sample_size, repeat,
            log_reg_date, max_model_size, max_expr_len, language_name)
        data = pd.read_csv(csv_fileloc / csv_filename)
        sns.distplot(data[f"coef_{ind_var1}"],
                     color="tab:blue",
                     ax=axs[0, ax],
                     label="Original")
        sns.distplot(data[f"coef_{ind_var2}"],
                     color="tab:orange",
                     ax=axs[0, ax],
                     label="Randomly shuffled")
        sns.distplot(data[f"{ind_var1}-{ind_var2}"],
                     ax=axs[1, ax],
                     color="tab:purple",
                     label="Original - Randomly shuffled")
    for ax in axs.flat:
        ax.set_ylim(0, 15)
        ax.set_xlim(-0.6, 0.6)
    axs[0, 0].set_ylabel("Density", fontsize=14)
    axs[1, 0].set_ylabel("Density", fontsize=14)

    for ax in range(1, len(dep_vars)):
        axs[0, ax].set_ylabel("")
        axs[1, ax].set_ylabel("")

    plt.rcParams['legend.handlelength'] = 1
    plt.rcParams['legend.handleheight'] = 1.125
    # plt.rcParams['legend.numpoints'] = 1
    # https://matplotlib.org/3.1.1/gallery/text_labels_and_
    # annotations/custom_legends.html
    custom_lines0 = [
        Patch(color="tab:blue", label="Original data"),
        Patch(color="tab:orange", label="Randomly shuffled")
    ]
    custom_lines1 = [Patch(color='tab:purple', label="Difference per sample")]
    for ax in range(len(dep_vars)):
        axs[0, ax].set_xlabel("")
        axs[1, ax].set_xlabel("Coefficient", fontsize=14)
        axs[0, ax].set_title(dep_vars_names[dep_vars[ax]], size=16)
    for ax in range(1, len(dep_vars)):
        axs[0, ax].set_yticklabels([])
        axs[1, ax].set_yticklabels([])
    axs[0, ax].legend(handles=custom_lines0,
                      loc="upper left",
                      bbox_to_anchor=(0.0, 1.0),
                      fontsize=12)
    axs[1, ax].legend(handles=custom_lines1,
                      loc="upper left",
                      bbox_to_anchor=(0.0, 1.0),
                      fontsize=12)
    plot_fileloc = utils.make_log_reg_plot_path(max_model_size, language_name,
                                                lang_gen_date, log_reg_date)
    basic_filename = utils.make_basic_filename(max_model_size, max_expr_len,
                                               language_name)
    plt.savefig(
        plot_fileloc / Path(f"{ind_var1}-{bootstrap_id}-repeat={repeat}-" + \
        f"samples={sample_size}-{basic_filename}.png"),
        dpi=600
    )
    plt.close()
def plot_mixture(repo_path):
    """
    Plots the results of mixture_mlp.py with 5 repetitions and 10 epochs for the three classification problems
    Run this code before if the synthetic_influence_target_X files do not exist:
    - python3 src/mixture_mlp.py -r 5 -e 10 -c 0
    - python3 src/mixture_mlp.py -r 5 -e 10 -c 1
    - python3 src/mixture_mlp.py -r 5 -e 10 -c 2

    :param repo_path:   path to repository
    :returns:           Mixture results plot saved in libs-pewpew/data/mixture_results as png and pdf
    """

    target_0 = np.load(
        os.path.join(repo_path, 'data/synthetic_influence_target_0.npy'))
    target_1 = np.load(
        os.path.join(repo_path, 'data/synthetic_influence_target_1.npy'))
    target_2 = np.load(
        os.path.join(repo_path, 'data/synthetic_influence_target_2.npy'))

    #calculate mean and standard deviation for each mixture result
    mean0 = np.array([np.mean(y) for y in target_0])
    mean1 = np.array([np.mean(y) for y in target_1])
    mean2 = np.array([np.mean(y) for y in target_2])
    std0 = np.array([np.std(y) for y in target_0])
    std1 = np.array([np.std(y) for y in target_1])
    std2 = np.array([np.std(y) for y in target_2])

    x_values = np.arange(0, 100.5, 5)

    fig, axs = plt.subplots(3, sharex=True, sharey=True, figsize=(7, 7))
    fig.subplots_adjust(bottom=0.15, top=0.92, left=0.15)

    plt.suptitle('Results for mixture of datasets', fontsize=16)
    plt.xlabel('Percentage of synthetic data added to handheld data',
               fontsize=10)
    plt.ylabel('Accuracy', fontsize=14)

    axs[0].plot(x_values, mean0, label='Classes', color='#0d627a')
    axs[0].plot(x_values[np.argmax(mean0)],
                mean0.max(),
                'o',
                color='black',
                markersize=4)
    axs[0].fill_between(x_values,
                        mean0 + std0,
                        mean0 - std0,
                        alpha=0.5,
                        facecolor='#0d627a')
    axs[0].set_title('Classes', position=(0.9, 0.3), fontsize=10)
    axs[0].set_ylabel('Accuracy', fontsize=10)

    axs[1].plot(x_values, mean1, label='Groups', color='#f2dc5c')
    axs[1].plot(x_values[np.argmax(mean1)],
                mean1.max(),
                'o',
                color='black',
                markersize=4)
    axs[1].fill_between(x_values,
                        mean1 + std1,
                        mean1 - std1,
                        alpha=0.5,
                        facecolor='#f2dc5c')
    axs[1].set_title('Groups', position=(0.9, 0.3), fontsize=10)
    axs[1].set_ylabel('Accuracy', fontsize=10)

    axs[2].plot(x_values, mean2, label='Minerals', color='#96cf6d')
    axs[2].plot(x_values[np.argmax(mean2)],
                mean2.max(),
                'o',
                color='black',
                markersize=4)
    axs[2].fill_between(x_values,
                        mean2 + std2,
                        mean2 - std2,
                        alpha=0.5,
                        facecolor='#96cf6d')
    axs[2].set_title('Minerals', position=(0.9, 0.3), fontsize=10)
    axs[2].set_ylabel('Accuracy', fontsize=10)

    legend_elements = [
        Line2D([0], [0], color='black', lw=2, label='Average accuracy'),
        Patch(facecolor='black', alpha=0.5, label='Standard deviation'),
        Line2D([0], [0],
               marker='o',
               color='w',
               label='Maximum accuracy',
               markerfacecolor='black',
               markersize=6),
    ]

    plt.legend(handles=legend_elements,
               loc='lower center',
               ncol=3,
               bbox_to_anchor=(0.5, -0.6))

    plt.savefig(
        os.path.join(repo_path, 'data/visualisations/mixture_results.pdf'))
    plt.savefig(
        os.path.join(repo_path, 'data/visualisations/mixture_results.png'))
Beispiel #25
0
    print(system, color)
    rect.set_edgecolor(color)
    rect.set_linewidth(10)

# add title
ax.set_title('$F_1$ development over the years for %s' % the_competition,
             fontsize=30)

# add legend
#'FS': 'mediumblue',
#'KB (S)': 'orange',
#'KB (U)': 'green',
#'Semi-S': 'red'

legend_elements = [
    Patch(facecolor='white', edgecolor='#0173B2', linewidth=8, label='FS'),
    Patch(facecolor='white', edgecolor='#DE8F05', linewidth=8, label='KB (S)'),
    Patch(facecolor='white', edgecolor='#029E73', linewidth=8, label='KB (U)'),
    Patch(facecolor='white', edgecolor='#D55E00', linewidth=8, label='Semi-S'),
]
lgd = ax.legend(handles=legend_elements,
                loc='center',
                fontsize=30,
                bbox_to_anchor=(1.1, 0.5))

# save plot
plt.savefig(output_path, bbox_extra_artists=(lgd, ), bbox_inches='tight')

title = 'F1 development'

plot_df.to_pickle(data_path)
Beispiel #26
0
)
for feature in transmembrane_annotation:
    loc = feature.locs[0]
    ax.axvspan(loc.first, loc.last, color=(0.0, 0.0, 0.0, 0.2), linewidth=0)

# Plot similarity score as measure for conservation
ax2 = ax.twinx()
ax2.plot(
    np.arange(1+ma_radius, len(hcn1)-ma_radius+1), scores,
    color=biotite.colors["brightorange"]
)
ax2.set_ylabel("Similarity score (15 residues moving average)")

ax.legend(
    handles=[
        Patch(color=biotite.colors["dimorange"],    label="Hydropathy"),
        Patch(color=biotite.colors["brightorange"], label="Score"     )
    ],
    fontsize=9
)

########################################################################
# The plot signifies two points:
# At first the transmembrane helices have a high hydropathy,
# as expected.
# Secondly the sequence conservation is extraordinarily high in the
# transmembrane region.
# 
# Finally the alignment itself is visualized.
# As this example focuses on the hydropathy, the colors of the symbols
# should illustrate the hydropathy of the respective amino acid.
Beispiel #27
0
def create_animation_frames(region):
    # create animation frames
    for l in range(plot_start, entries + 4):
        current_date_index = l  # index of the last data point to be used
        desired_fit_count = 3  # number of previous fits to include

        if l > entries:  # used to fade out the last three plots
            current_date_index = entries
            desired_fit_count = 3 - (l - current_date_index) + 1

        data_x = np.arange(0, current_date_index)
        china_data_y = confirmed_by_region[MAINLAND_CHINA][
            0:current_date_index]

        row_data_y = (
            confirmed_total -
            confirmed_by_region[MAINLAND_CHINA])[0:current_date_index]

        # creation of pyplot plot
        fig, (ax_regional_development, ax_shared) = plt.subplots(2)
        ax_shared.yaxis.tick_right()
        ax_shared.yaxis.set_label_position("right")
        ax_shared.spines["left"].set_color("none")
        ax_regional_development.yaxis.tick_right()
        ax_regional_development.yaxis.set_label_position("right")
        ax_regional_development.spines["left"].set_color("none")

        # setting the dimensions (basically resolution with 12by9 aspect ratio)
        fig.set_figheight(12)
        fig.set_figwidth(12)

        majxticks = ([], [])
        # generation of x-axis tick-names
        startdate = datetime(2020, 1, 22)
        for j in range(xmin, xmax + 1, xstep):
            majxticks[0].append(j)
            majxticks[1].append((startdate + timedelta(j)).strftime("%d. %b"))

        # setting the x-axis ticks
        ax_shared.set_xlim([xmin, xmax])
        ax_shared.set_xticks(majxticks[0])
        ax_shared.set_xticklabels(majxticks[1])
        ax_shared.xaxis.set_minor_locator(MultipleLocator(1))

        # ax_regional_development.set_ylim([0, 1])
        ax_regional_development.set_xlim([xmin, xmax])
        ax_regional_development.set_xticks(majxticks[0])
        ax_regional_development.set_xticklabels(majxticks[1])
        ax_regional_development.xaxis.set_minor_locator(MultipleLocator(1))

        # setting the y-axis ticks
        shared_lim_ticks_labels = get_yaxis_lim_ticks_labels(
            np.max([
                confirmed_by_region[MAINLAND_CHINA][current_date_index - 1],
                row_data_y[current_date_index - 1],
            ]))
        ax_shared.set_ylim(shared_lim_ticks_labels[0])
        ax_shared.set_yticks(shared_lim_ticks_labels[1])
        ax_shared.set_yticklabels(shared_lim_ticks_labels[2])
        ax_shared.yaxis.set_minor_locator(
            MultipleLocator(shared_lim_ticks_labels[1][1] / 2))

        regional_lim_ticks_labels = get_yaxis_lim_ticks_labels(
            confirmed_by_region[region][current_date_index - 1])
        ax_regional_development.set_ylim(regional_lim_ticks_labels[0])
        ax_regional_development.set_yticks(regional_lim_ticks_labels[1])
        ax_regional_development.set_yticklabels(regional_lim_ticks_labels[2])
        ax_regional_development.yaxis.set_minor_locator(
            MultipleLocator(regional_lim_ticks_labels[1][1] / 2))

        # label axis
        plt.xlabel("date")
        ax_shared.set_ylabel("total # of confirmed infections")
        ax_regional_development.set_ylabel("total # of confirmed infections")

        # format the border of the diagram
        ax_shared.spines["top"].set_color("white")
        ax_regional_development.spines["top"].set_color("white")

        # plot the original data
        ax_shared.plot(data_x,
                       china_data_y,
                       "s",
                       color=china_color,
                       markersize=7,
                       zorder=10)
        ax_shared.fill_between(
            data_x,
            np.zeros(current_date_index),
            recovered_by_region[MAINLAND_CHINA][:current_date_index],
            color=china_recovered_color,
            alpha=0.5,
            hatch="//",
        )
        ax_shared.fill_between(
            data_x,
            recovered_by_region[MAINLAND_CHINA][:current_date_index],
            recovered_by_region[MAINLAND_CHINA][:current_date_index] +
            dead_by_region[MAINLAND_CHINA][:current_date_index],
            color=china_dead_color,
            alpha=0.5,
            hatch="//",
        )
        ax_shared.fill_between(
            data_x,
            recovered_by_region[MAINLAND_CHINA][:current_date_index] +
            dead_by_region[MAINLAND_CHINA][:current_date_index],
            china_data_y,
            color=china_color,
            alpha=0.2,
            hatch="//",
        )

        recovered_row = (
            recovered_total[:current_date_index] -
            recovered_by_region[MAINLAND_CHINA][:current_date_index])
        dead_row = (dead_total[:current_date_index] -
                    dead_by_region[MAINLAND_CHINA][:current_date_index])
        ax_shared.plot(data_x,
                       row_data_y,
                       "o",
                       color=row_color,
                       markersize=7,
                       zorder=10)
        ax_shared.fill_between(
            data_x,
            np.zeros(current_date_index),
            recovered_row,
            color=row_recovered_color,
            alpha=0.5,
            hatch="..",
        )
        ax_shared.fill_between(
            data_x,
            recovered_row,
            recovered_row + dead_row,
            color=row_dead_color,
            alpha=0.5,
            hatch="..",
        )
        ax_shared.fill_between(
            data_x,
            recovered_row + dead_row,
            row_data_y,
            color=row_color,
            alpha=0.2,
            hatch="..",
        )

        i = current_date_index - plot_start

        for k in range(
                0, np.min([desired_fit_count,
                           current_date_index - plot_start])):
            b = china_fits[i - k][0][1]
            # fit the exponential function
            func = get_row_fit_function(b)
            jac = get_row_fit_jacobian(b)
            try:
                popt, pcov = scipy.optimize.curve_fit(
                    func,
                    data_x[:current_date_index - k],
                    confirmed_by_region[region][:current_date_index - k],
                    p0=[1000000, 20],
                    jac=jac,
                    maxfev=10000,
                )
            except Exception as e:
                print(e)
                print(i)
                print(k)
                print(i - k)

            # get errors from trace of covariance matrix
            perr = np.sqrt(np.diag(pcov))

            # create uncertainty floats for error bars, 2* means 2 sigma
            a = ufloat(popt[0], perr[0])
            c = ufloat(popt[1], perr[1])

            # get the values of the uncertain fit
            fit_x_unc = np.linspace(xmin, xmax, 300)
            fit_y_unc = a / (1 + unp.exp(-b * (fit_x_unc - c)))
            nom_x = unp.nominal_values(fit_x_unc)
            nom_y = unp.nominal_values(fit_y_unc)
            std_y = unp.std_devs(fit_y_unc)

            # plot
            if k == 0:
                print("[" +
                      (startdate +
                       timedelta(current_date_index)).strftime("%d. %b") +
                      "] ROW fit(y=a*exp(b*x))-parameters:")
                print("a = " + str(a))
                print("b = " + str(b))

                ax_regional_development.plot(
                    nom_x,
                    nom_y,
                    color=regional_regression_color,
                    linewidth=3,
                    linestyle=":",
                    alpha=0.7,
                )
                ax_regional_development.fill_between(
                    nom_x,
                    nom_y - std_y,
                    nom_y + std_y,
                    facecolor=regional_regression_color,
                    alpha=0.3,
                )
            elif k == 1:
                ax_regional_development.fill_between(
                    nom_x,
                    nom_y - std_y,
                    nom_y + std_y,
                    facecolor=regional_regression_color,
                    alpha=0.1,
                )
            elif k == 2:
                ax_regional_development.fill_between(
                    nom_x,
                    nom_y - std_y,
                    nom_y + std_y,
                    facecolor=regional_regression_color,
                    alpha=0.05,
                )

        for k in range(
                0, np.min([desired_fit_count,
                           current_date_index - plot_start])):
            # fit the sigmoidal function
            popt, pcov = scipy.optimize.curve_fit(
                _row_fit_function,
                data_x[:current_date_index - k],
                row_data_y[:current_date_index - k],
                jac=_row_fit_jacobian,
                maxfev=10000,
            )
            # get errors from trace of covariance matrix
            perr = np.sqrt(np.diag(pcov))

            # create uncertainty floats for error bars, 2* means 2 sigma
            a = ufloat(popt[0], perr[0])
            b = ufloat(popt[1], perr[1])

            # get the values of the uncertain fit
            fit_x_unc = np.linspace(xmin, xmax, 300)
            fit_y_unc = a * unp.exp(b * fit_x_unc)
            nom_x = unp.nominal_values(fit_x_unc)
            nom_y = unp.nominal_values(fit_y_unc)
            std_y = unp.std_devs(fit_y_unc)

            # plot
            if k == 0:
                print("[" +
                      (startdate +
                       timedelta(current_date_index)).strftime("%d. %b") +
                      "] China fit(y=a/(1+exp(-b*(x-c))))-parameters:")
                print("a = " + str(a))
                print("b = " + str(b))
                ax_shared.plot(nom_x,
                               nom_y,
                               color=row_regression_color,
                               linewidth=3)
                ax_shared.fill_between(
                    nom_x,
                    nom_y - std_y,
                    nom_y + std_y,
                    facecolor=row_regression_color,
                    alpha=0.6,
                )
            elif k == 1:
                ax_shared.fill_between(
                    nom_x,
                    nom_y - std_y,
                    nom_y + std_y,
                    facecolor=row_regression_color,
                    alpha=0.2,
                )
            elif k == 2:
                ax_shared.fill_between(
                    nom_x,
                    nom_y - std_y,
                    nom_y + std_y,
                    facecolor=row_regression_color,
                    alpha=0.1,
                )

        for k in range(
                0, np.min([desired_fit_count,
                           current_date_index - plot_start])):
            # fit the sigmoidal function
            popt, pcov = china_fits[i - k]
            # get errors from trace of covariance matrix
            perr = np.sqrt(np.diag(pcov))

            # create uncertainty floats for error bars, 2* means 2 sigma
            a = ufloat(popt[0], perr[0])
            b = ufloat(popt[1], perr[1])
            c = ufloat(popt[2], perr[2])

            # get the values of the uncertain fit
            fit_x_unc = np.linspace(xmin, xmax, 300)
            fit_y_unc = a / (1 + unp.exp(-b * (fit_x_unc - c)))
            nom_x = unp.nominal_values(fit_x_unc)
            nom_y = unp.nominal_values(fit_y_unc)
            std_y = unp.std_devs(fit_y_unc)

            # plot
            if k == 0:
                print("[" +
                      (startdate +
                       timedelta(current_date_index)).strftime("%d. %b") +
                      "] China fit(y=a/(1+exp(-b*(x-c))))-parameters:")
                print("a = " + str(a))
                print("b = " + str(b))
                print("c = " + str(c))
                ax_shared.plot(nom_x,
                               nom_y,
                               color=china_regression_color,
                               linewidth=3)
                ax_shared.fill_between(
                    nom_x,
                    nom_y - std_y,
                    nom_y + std_y,
                    facecolor=china_regression_color,
                    alpha=0.6,
                )
            elif k == 1:
                ax_shared.fill_between(
                    nom_x,
                    nom_y - std_y,
                    nom_y + std_y,
                    facecolor=china_regression_color,
                    alpha=0.2,
                )
            elif k == 2:
                ax_shared.fill_between(
                    nom_x,
                    nom_y - std_y,
                    nom_y + std_y,
                    facecolor=china_regression_color,
                    alpha=0.1,
                )

        plt.tight_layout()

        ax_regional_development.set_title("regional development in " +
                                          region_names[region])
        ax_regional_development.plot(
            data_x,
            confirmed_by_region[region][:current_date_index],
            color=regional_total_color,
            lw=4,
        )
        ax_regional_development.bar(
            data_x,
            new_cases_by_region[region][:current_date_index],
            color=regional_change_color,
        )

        # these objects are used to create a consistent legend
        legendel_regional_total = Line2D([0], [0],
                                         color=regional_total_color,
                                         lw=4)
        legendel_regional_change = Patch(facecolor=regional_change_color)
        legendel_regional_fit = Line2D(
            [0],
            [0],
            color=regional_regression_color,
            linewidth=3,
            linestyle=":",
            alpha=0.7,
        )

        # add the legend and object descriptions
        piechart_legend = ax_regional_development.legend(
            [
                legendel_regional_total, legendel_regional_change,
                legendel_regional_fit
            ],
            [
                "Total cases", "New cases",
                "Fit assuming the same\ngrowth as in China"
            ],
            loc="upper left",
        )
        piechart_legend.get_frame().set_edgecolor("black")
        piechart_legend.set_zorder(20)

        legendel_china_data = Line2D(
            [0],
            [0],
            marker="s",
            color=china_color,
            lw=0,
            markerfacecolor=china_color,
            markersize=10,
        )
        legendel_china_regression = Line2D([0], [0],
                                           color=china_regression_color,
                                           lw=4)
        legendel_china_recovered = Patch(
            facecolor=china_recovered_color,
            alpha=0.5,
            hatch="//",
            edgecolor=china_recovered_color,
        )
        legendel_china_dead = Patch(
            facecolor=china_dead_color,
            alpha=0.5,
            hatch="//",
            edgecolor=china_dead_color,
        )
        legendel_spacer = Patch(facecolor="none")
        legendel_row_data = Line2D(
            [0],
            [0],
            marker="o",
            color=row_color,
            lw=0,
            markerfacecolor=row_color,
            markersize=10,
        )
        legendel_row_regression = Line2D([0], [0],
                                         color=row_regression_color,
                                         lw=4)
        legendel_row_recovered = Patch(
            facecolor=row_recovered_color,
            alpha=0.5,
            hatch="..",
            edgecolor=row_recovered_color,
        )
        legendel_row_dead = Patch(
            facecolor=row_dead_color,
            alpha=0.5,
            hatch="..",
            edgecolor=row_dead_color,
        )
        total_legend = ax_shared.legend(
            [
                legendel_china_data,
                legendel_china_regression,
                legendel_china_recovered,
                legendel_china_dead,
                legendel_row_data,
                legendel_row_regression,
                legendel_row_recovered,
                legendel_row_dead,
            ],
            [
                "Infections in China",
                "Adoption to an sigmoidal fit",
                "Recovered cases in China",
                "COVID-19 deaths in China",
                "Infections outside China",
                "Adoption to an exponential fit",
                "Recovered cases outside China",
                "COVID-19 deaths outside China",
            ],
            loc="upper left",
        )
        total_legend.get_frame().set_edgecolor("black")
        total_legend.set_zorder(20)

        # save the plot in the current folder
        plt.tight_layout()
        plt.savefig(f"./images/{region}_{l}.png")

        if l == entries + 3:
            plt.savefig(f"./images/{region}_highres.png", dpi=500)

        time.sleep(0.1)
        plt.close()
Beispiel #28
0
def plot_depth(image_key, pixel_age, flag_map, # validity_map,
               depth_map_true, depth_map_pred, variance_map,
               image_cmap="gray", depth_cmap='RdBu'):

    fig = plt.figure()

    ax = fig.add_subplot(2, 4, 1)
    ax.set_title("keyframe")
    ax.imshow(image_key, cmap=image_cmap)

    ax = fig.add_subplot(2, 4, 2)
    ax.set_title("pixel age")
    im = ax.imshow(pixel_age, cmap=image_cmap)
    plot_with_bar(ax, im)

    ax = fig.add_subplot(2, 4, 3)
    ax.set_title("flag map")
    ax.imshow(flag_to_color_map(flag_map))
    patches = [Patch("black", flag_to_rgb(f), label=f.name) for f in FLAG]
    ax.legend(handles=patches, loc='center left', bbox_to_anchor=(1.05, 0.5))

    mask = flag_map==FLAG.SUCCESS

    if mask.sum() == 0:  # no success pixel
        plt.show()
        return

    depths_pred = depth_map_pred[mask]
    depths_true = depth_map_true[mask]
    depths_diff = np.abs(depths_pred - depths_true)

    us = image_coordinates(depth_map_pred.shape)[mask.flatten()]

    vmax = np.percentile(
        np.concatenate((depth_map_true.flatten(), depths_pred)), 98
    )
    norm = Normalize(vmin=0.0, vmax=vmax)
    mapper = ScalarMappable(norm=norm, cmap=depth_cmap)

    ax = fig.add_subplot(2, 4, 5)
    ax.set_title("ground truth depth")
    ax.axis("off")
    im = ax.imshow(depth_map_true, norm=norm, cmap=depth_cmap)
    plot_with_bar(ax, im)

    height, width = image_key.shape[0:2]

    ax = fig.add_subplot(2, 4, 6)
    ax.set_title("predicted depth map")
    ax.axis("off")
    im = ax.imshow(image_key, cmap=image_cmap)
    ax.scatter(us[:, 0], us[:, 1], s=0.5, c=mapper.to_rgba(depths_pred))
    ax.set_xlim(0, width)
    ax.set_ylim(height, 0)

    ax = fig.add_subplot(2, 4, 7)
    ax.set_title("error = abs(pred - true)")
    im = ax.imshow(image_key, cmap=image_cmap)
    ax.scatter(us[:, 0], us[:, 1], s=0.5, c=mapper.to_rgba(depths_diff))
    ax.set_xlim(0, width)
    ax.set_ylim(height, 0)

    ax = fig.add_subplot(2, 4, 8)
    ax.set_title("variance map")
    norm = Normalize(vmin=0.0, vmax=np.percentile(variance_map.flatten(), 98))
    im = ax.imshow(variance_map, norm=norm, cmap=depth_cmap)
    plot_with_bar(ax, im)

    plt.show()
Beispiel #29
0
plt.tick_params(labelcolor='none',
                which='both',
                top=False,
                bottom=False,
                left=False,
                right=False)
plt.xlabel("Year", fontsize=24, labelpad=20)
plt.ylabel("Crop area as percentage of available arable area",
           fontsize=24,
           labelpad=20)

legend_elements = [
    Line2D([0], [0], color='black', lw=2, label='worst case'),
    Line2D([0], [0], color='black', lw=2, ls="dashdot", label='stationary'),
    Line2D([0], [0], color='black', lw=2, ls="--", label='best case'),
    Patch(color=col1, label='Rice'),
    Patch(color=col2, label='Maize')
]
ax.legend(handles=legend_elements,
          fontsize=18,
          bbox_to_anchor=(0.5, -0.15),
          loc="upper center",
          ncol=2)

panelA.savefig("Figures/PublicationPlots/SI/Figure4Alternative_CropAreas.jpg",
               bbox_inches="tight",
               pad_inches=1,
               format="jpg")
plt.close(panelA)

# %%  CROP AREAS  -- ALTERNATIVE
def plot_read_counts_v2(labels,
                        counts,
                        labels_in_run,
                        possible_labels=None,
                        ax=None,
                        vmax=None,
                        title_note=None):
    from matplotlib.patches import Patch

    bit0_facecolor = "tab:gray"
    bit0_textcolor = "tab:gray"
    bit1_facecolor = "tab:blue"
    bit1_textcolor = "k"

    if vmax is None:
        vmax = max(counts) + max(int(0.1 * max(counts)), 100)
    if ax == None:
        fig, ax = plt.subplots(figsize=(30, 8))
    if possible_labels is None:
        possible_labels = labels[:]
    g = sns.barplot(x=labels, y=counts, order=possible_labels, ax=ax)
    title = "#/reads identified per molbit"
    if title_note is not None:
        title += "\n(%s)" % title_note
    ax.set_title(title)
    ax.set_xlabel("Molbit ID")
    ax.set_ylabel("Read counts")
    ax.set_ylim([0, vmax])

    prev_text_height = 0
    for j, label in enumerate(possible_labels):
        if label in labels:
            count = counts[labels.index(label)]
        else:
            count = 0
        if label == "-1":
            continue

        if label in labels_in_run:
            g.containers[0].get_children()[j].set_facecolor(bit1_facecolor)
            font_kwargs = {"color": bit1_textcolor, "weight": "normal"}
        else:
            g.containers[0].get_children()[j].set_facecolor(bit0_facecolor)
            font_kwargs = {"color": bit0_textcolor, "weight": "normal"}

        rotate_text = 0
        diff = prev_text_height - (count + 0.01 * vmax)
        if count < 100:
            text_height = count + .01 * vmax
            ax.text(j,
                    text_height,
                    count,
                    ha="center",
                    rotation=rotate_text,
                    **font_kwargs)
        elif diff < 0 and np.abs(diff) < vmax * .06:
            text_height = np.max(
                [prev_text_height + .035 * vmax, count + .01 * vmax])
            ax.text(j,
                    text_height,
                    count,
                    ha="center",
                    rotation=rotate_text,
                    **font_kwargs)
        elif np.abs(diff) < vmax * .05:
            text_height = np.min(
                [prev_text_height - .03 * vmax, count + .01 * vmax])
            ax.text(j,
                    text_height,
                    count,
                    ha="center",
                    rotation=rotate_text,
                    **font_kwargs)
        else:
            text_height = count + .01 * vmax
            ax.text(j,
                    text_height,
                    count,
                    ha="center",
                    rotation=rotate_text,
                    **font_kwargs)
        prev_text_height = text_height

    legend_elements = [
        Patch(facecolor=bit0_facecolor,
              edgecolor=bit0_facecolor,
              label='0-bits'),
        Patch(facecolor=bit1_facecolor,
              edgecolor=bit1_facecolor,
              label='1-bits')
    ]
    leg = ax.legend(handles=legend_elements)
    t1, t2 = leg.get_texts()
    t2._fontproperties = t1._fontproperties.copy()
    t2.set_weight('normal')
    t1.set_weight('normal')
    t2.set_color(bit1_textcolor)
    t1.set_color(bit0_textcolor)
    return ax
Beispiel #31
0
def run():
    plt.figure(figsize=(8, 6))
    p = Palette()
    award_color = p.magenta()
    enrol_color = p.cyan()
    plt.bar(len(others_labels) - 1, phd[1][1], color=enrol_color, zorder=3)
    total = sum(others_values[1:])  # Last 6 years
    x = len(others_labels) - 1
    plt.plot([x - 0.5, x + 0.5], [total, total], color="k", ls="--", zorder=3)
    plt.annotate("Total PhD awarded in last 6 years\n(2012-2018)",
                 xy=(x - 0.55, total),
                 xytext=(x - 2.3, total - 30000),
                 ha="center",
                 arrowprops=dict(arrowstyle="->",
                                 connectionstyle="angle",
                                 ec=p.gray(shade=70)))
    for i in range(len(others_values)):
        plt.bar(i, others_values[i], color=award_color, zorder=3)
    plt.gca().set_facecolor(p.gray(shade=20))
    plt.xticks(range(len(others_labels)), others_labels)
    plt.bar(0, phd[0][1], color=enrol_color, zorder=2)
    plt.annotate("Total PhD enrolment\nfor 2010-11",
                 xy=(0, phd[0][1] + 1000),
                 ha="center",
                 va="bottom")
    plt.annotate("Total PhD enrolment\nfor 2017-18",
                 xy=(len(others_values) - 1, phd[1][1] + 1000),
                 ha="center",
                 va="bottom")

    plt.annotate(
        "Assuming average time it takes\nto complete the PhD in "
        "India is 5-6 years with\n avg of 125K candidates "
        "enrolling each year,\n"
        "at the end of 6th year only 21% gets their PhD.",
        xy=(0.5, 0.455),
        xycoords="axes fraction",
        ha="center",
        va="center")

    plt.xlim(-1.5, len(others_values) + 0.5)
    plt.ylim(0, 190000)

    handles = [
        Patch(fc=enrol_color, label="PhD Enrolment"),
        Patch(fc=award_color, label="PhD Awarded")
    ]
    legend = plt.legend(handles=handles,
                        loc='upper left',
                        bbox_to_anchor=(0, 0.99),
                        fancybox=True,
                        ncol=2)
    frame = legend.get_frame()
    frame.set_facecolor('w')
    frame.set_alpha(1)
    plt.ylabel("Number of Candidates")
    plt.xlabel("Academic Year")
    plt.title("Total PhD Enrolment and Awards granted by UGC")
    plt.grid(axis="y", ls=":", color=p.gray(shade=50), zorder=1)
    plt.tight_layout()
    plt.savefig("plot.png", dpi=300)
    plt.show()
Beispiel #32
0
 def __init__(self, path, **kwargs):
     zs = kwargs.pop("zs", [])
     zdir = kwargs.pop("zdir", "z")
     Patch.__init__(self, **kwargs)
     self.set_3d_properties(path, zs, zdir)
Beispiel #33
0
def _datashade_points(
    points,
    ax=None,
    labels=None,
    values=None,
    cmap="Blues",
    color_key=None,
    color_key_cmap="Spectral",
    background="white",
    width=800,
    height=800,
    show_legend=True,
):
    """Use datashader to plot points"""
    extent = _get_extent(points)
    canvas = ds.Canvas(
        plot_width=width,
        plot_height=height,
        x_range=(extent[0], extent[1]),
        y_range=(extent[2], extent[3]),
    )
    data = pd.DataFrame(points, columns=("x", "y"))

    legend_elements = None

    # Color by labels
    if labels is not None:
        if labels.shape[0] != points.shape[0]:
            raise ValueError("Labels must have a label for "
                             "each sample (size mismatch: {} {})".format(
                                 labels.shape[0], points.shape[0]))

        data["label"] = pd.Categorical(labels)
        aggregation = canvas.points(data, "x", "y", agg=ds.count_cat("label"))
        if color_key is None and color_key_cmap is None:
            result = tf.shade(aggregation, how="eq_hist")
        elif color_key is None:
            unique_labels = np.unique(labels)
            num_labels = unique_labels.shape[0]
            color_key = _to_hex(
                plt.get_cmap(color_key_cmap)(np.linspace(0, 1, num_labels)))
            legend_elements = [
                Patch(facecolor=color_key[i], label=k)
                for i, k in enumerate(unique_labels)
            ]
            result = tf.shade(aggregation, color_key=color_key, how="eq_hist")
        else:
            legend_elements = [
                Patch(facecolor=color_key[k], label=k)
                for k in color_key.keys()
            ]
            result = tf.shade(aggregation, color_key=color_key, how="eq_hist")

    # Color by values
    elif values is not None:
        if values.shape[0] != points.shape[0]:
            raise ValueError("Values must have a value for "
                             "each sample (size mismatch: {} {})".format(
                                 values.shape[0], points.shape[0]))
        unique_values = np.unique(values)
        if unique_values.shape[0] >= 256:
            min_val, max_val = np.min(values), np.max(values)
            bin_size = (max_val - min_val) / 255.0
            data["val_cat"] = pd.Categorical(
                np.round((values - min_val) / bin_size).astype(np.int16))
            aggregation = canvas.points(data,
                                        "x",
                                        "y",
                                        agg=ds.count_cat("val_cat"))
            color_key = _to_hex(plt.get_cmap(cmap)(np.linspace(0, 1, 256)))
            result = tf.shade(aggregation, color_key=color_key, how="eq_hist")
        else:
            data["val_cat"] = pd.Categorical(values)
            aggregation = canvas.points(data,
                                        "x",
                                        "y",
                                        agg=ds.count_cat("val_cat"))
            color_key_cols = _to_hex(
                plt.get_cmap(cmap)(np.linspace(0, 1, unique_values.shape[0])))
            color_key = dict(zip(unique_values, color_key_cols))
            result = tf.shade(aggregation, color_key=color_key, how="eq_hist")

    # Color by density (default datashader option)
    else:
        aggregation = canvas.points(data, "x", "y", agg=ds.count())
        result = tf.shade(aggregation, cmap=plt.get_cmap(cmap))

    if background is not None:
        result = tf.set_background(result, background)

    if ax is not None:
        _embed_datashader_in_an_axis(result, ax)
        if show_legend and legend_elements is not None:
            ax.legend(handles=legend_elements)
        return ax
    else:
        return result
Beispiel #34
0
 def __init__(self, path, *, zs=(), zdir='z', **kwargs):
     Patch.__init__(self, **kwargs)
     self.set_3d_properties(path, zs, zdir)
Beispiel #35
0
 def draw(self, renderer):
     Patch.draw(self, renderer)
    def plot_experiments_results_with_scikit_learn(self, lines_scores):
        """
        Plots experiments' results from scikit learn
        :param lines_scores: dict
        :return: void
        """
        test_years = ['13', '14', '15']
        markers = ['o', 'D', 'h', '*', '+']
        plot_types = ['-', '--', '-.', ':', ',']
        legend_line_names = {
            'line1': 'LINE1',
            'line2': 'LINE2',
            'line3L0': 'LINE3-MultinomialNB DB',
            'line3L1': 'LINE3-kMEANS CLUSTERING',
            'line3L2': 'LINE3-kMEANS CLUSTERING(probabilities)',
            'line3L3': 'LINE3-MultinomialNB DB Iterative Approach',
            'line4': 'LINE4'
        }
        # -(2012-500)/(YEAR-300)
        # -(2012-500)+(YEAR-R50)/(YEAR-300)
        # -(2012-500)+(YEAR-L50)/(YEAR-300)
        # -(2012-500)+(YEAR-L50)/(YEAR-300)
        # -(2012-500)+(YEAR-200)/(YEAR-300)
        fig, ax = plt.subplots(figsize=(20, 9))
        ax.set_autoscale_on(False)
        ax.set_xlim([12.5, 15.5])

        all_of_min = 100
        all_of_max = 0

        handles = []
        color_index = 0
        for first_iteration_number, (line_name, line_points) in enumerate(
                lines_scores.iteritems()):
            line_max, line_min = 0, 100

            if line_name == "line2":
                line_points_array = np.array(line_points.values())
                ys = line_points_array[:, 1]
                mins = line_points_array[:, 0]
                maxs = line_points_array[:, 2]
                line_max, line_min = np.max(maxs), np.min(mins)

                for sub_iteration_number, (a_min,
                                           a_max) in enumerate(zip(mins,
                                                                   maxs)):
                    ax.plot((int(test_years[sub_iteration_number]) - 0.05,
                             int(test_years[sub_iteration_number]) + 0.05),
                            (a_min, a_min), 'k-')
                    ax.plot((int(test_years[sub_iteration_number]) - 0.05,
                             int(test_years[sub_iteration_number]) + 0.05),
                            (a_max, a_max), 'k-')
                    ax.plot((int(test_years[sub_iteration_number]),
                             int(test_years[sub_iteration_number])),
                            (a_min, a_max), 'k-')

                ax.plot(test_years,
                        ys,
                        self.__colors[color_index],
                        marker=markers[first_iteration_number],
                        linestyle=plot_types[first_iteration_number],
                        linewidth=3.0)
                patch = Patch(color=self.__colors[color_index],
                              label=legend_line_names[line_name])
                color_index += 1
                handles.append(patch)

            elif line_name == "line3":
                for sub_iteration_number, (
                        ale_experiment_key) in enumerate(ALE_LINE3_KEYS):
                    proper_dict_values = [
                        line_points[dict_key]
                        for dict_key in line_points.keys()
                        if dict_key.startswith(ale_experiment_key)
                    ]
                    ys = proper_dict_values

                    line_max, line_min = np.max(ys), np.min(ys)
                    ax.plot(test_years,
                            ys,
                            self.__colors[color_index],
                            marker=markers[first_iteration_number],
                            linestyle=plot_types[first_iteration_number],
                            linewidth=3.0)
                    patch = Patch(color=self.__colors[color_index],
                                  label=legend_line_names[line_name +
                                                          ale_experiment_key])
                    handles.append(patch)
                    color_index += 1
            else:
                ys = line_points.values()
                line_max, line_min = np.max(ys), np.min(ys)
                ax.plot(test_years,
                        ys,
                        self.__colors[color_index],
                        marker=markers[first_iteration_number],
                        linestyle=plot_types[first_iteration_number],
                        linewidth=3.0)
                patch = Patch(color=self.__colors[color_index],
                              label=legend_line_names[line_name])
                handles.append(patch)
                color_index += 1
            all_of_min = min(line_min, all_of_min)
            all_of_max = max(line_max, all_of_max)

        ymin = all_of_min - 0.01
        ymax = all_of_max + 0.01

        plt.legend(handles=handles)

        ax.set_ylim([ymin, ymax])
        plt.yticks(np.arange(ymin, ymax, 0.01))
        ax.set_xticklabels(["", "13", "", "14", "", "15"])
        plt.xlabel('Years')
        plt.ylabel('Scores %')
        plt.title(
            'Scores by year with changing training sets. Classifier=SVM Feature=Word.'
        )
        plt.tight_layout()
        plt.grid()
        plt.show()
            ax.set_ylim(Y_LIMS2)

        if row_id == NUM_ROWS - 1:
            ax.set_xticks([1, 2])
            ax.set_xticklabels(X_TICK_LABELS)
        else:
            ax.set_xticks([])
            ax.set_xticklabels([])

        ax.grid(axis='y')

        # plot 2 groups of 2 bars: both age groups, and raw vs. normalized data
        x = [1 - WIDTH / 2, 1 + WIDTH / 2, 2 - WIDTH / 2, 2 + WIDTH / 2]
        ax.bar(x, y, color=['C0', 'C1', 'C0', 'C1'], width=WIDTH, zorder=3)

legend_elements = [
    Patch(facecolor='C0', label='age group 1'),
    Patch(facecolor='C1', label='age group 2')
]
fig.legend(
    handles=legend_elements,
    prop={'size': 12},
    bbox_to_anchor=(0.5, 0.2),  # distance from bottom-left
    loc='upper center',
    frameon=False)

# TODO this script must be run in terminal so that subplots are close to each other

# fig.set_constrained_layout_pads(h_pad=0, hspace=500, wspace=330)
plt.show()
Beispiel #38
0
def _matplotlib_points(
    points,
    ax=None,
    labels=None,
    values=None,
    cmap="Blues",
    color_key=None,
    color_key_cmap="Spectral",
    background="white",
    width=800,
    height=800,
    show_legend=True,
):
    """Use matplotlib to plot points"""
    point_size = 100.0 / np.sqrt(points.shape[0])

    legend_elements = None

    if ax is None:
        dpi = plt.rcParams["figure.dpi"]
        fig = plt.figure(figsize=(width / dpi, height / dpi))
        ax = fig.add_subplot(111)

    ax.set_facecolor(background)

    # Color by labels
    if labels is not None:
        if labels.shape[0] != points.shape[0]:
            raise ValueError("Labels must have a label for "
                             "each sample (size mismatch: {} {})".format(
                                 labels.shape[0], points.shape[0]))
        if color_key is None:
            unique_labels = np.unique(labels)
            num_labels = unique_labels.shape[0]
            color_key = plt.get_cmap(color_key_cmap)(np.linspace(
                0, 1, num_labels))
            legend_elements = [
                Patch(facecolor=color_key[i], label=unique_labels[i])
                for i, k in enumerate(unique_labels)
            ]

        if isinstance(color_key, dict):
            colors = pd.Series(labels).map(color_key)
            unique_labels = np.unique(labels)
            legend_elements = [
                Patch(facecolor=color_key[k], label=k) for k in unique_labels
            ]
        else:
            unique_labels = np.unique(labels)
            if len(color_key) < unique_labels.shape[0]:
                raise ValueError(
                    "Color key must have enough colors for the number of labels"
                )

            new_color_key = {
                k: color_key[i]
                for i, k in enumerate(unique_labels)
            }
            legend_elements = [
                Patch(facecolor=color_key[i], label=k)
                for i, k in enumerate(unique_labels)
            ]
            colors = pd.Series(labels).map(new_color_key)

        ax.scatter(points[:, 0], points[:, 1], s=point_size, c=colors)

    # Color by values
    elif values is not None:
        if values.shape[0] != points.shape[0]:
            raise ValueError("Values must have a value for "
                             "each sample (size mismatch: {} {})".format(
                                 values.shape[0], points.shape[0]))
        ax.scatter(points[:, 0],
                   points[:, 1],
                   s=point_size,
                   c=values,
                   cmap=cmap)

    # No color (just pick the midpoint of the cmap)
    else:

        color = plt.get_cmap(cmap)(0.5)
        ax.scatter(points[:, 0], points[:, 1], s=point_size, c=color)

    if show_legend and legend_elements is not None:
        ax.legend(handles=legend_elements)

    return ax
Beispiel #39
0
               cmap=matplotlib.colors.ListedColormap(utils.default_colors,
                                                     N=N),
               depthshade=False,
               s=10)
    ax.set_xlabel('PC1')
    ax.set_ylabel('PC2')
    ax.set_zlabel('PC3')
    plt.title('HDBSCAN (all)')

    legend_elements = []
    from matplotlib.patches import Patch
    for i in range(N):
        n_elements = np.unique(sub_colors, return_counts=True)[1][i]
        legend_elements.append(
            Patch(facecolor=utils.default_colors[i],
                  edgecolor='black',
                  label='{} elements'.format(n_elements)))
    legend = ax.legend(handles=legend_elements, loc='upper right')
    plt.show(block=False)
    plt.pause(0.001)

    if input('\nWant the means? (y|N)\n') != 'y':
        print('ok')
    else:
        clusters_list = []
        mean_waves = np.zeros((N, 780))
        for i in range(N - 1):  # -1 because the noise is not included
            # Mean acquiring:
            print(waves[i == labels].shape)
            clusters_list.append(waves[i == labels, :])
            mean_waves[i] = np.mean(waves[i == labels], axis=0)
Beispiel #40
0
 def __init__(self, path, **kwargs):
     zs = kwargs.pop('zs', [])
     zdir = kwargs.pop('zdir', 'z')
     Patch.__init__(self, **kwargs)
     self.set_3d_properties(path, zs, zdir)
Beispiel #41
0
           linestyle=":",
           ax=axes[0])

axes[0].set_title("A) Three uncertain parameters", fontsize=titlesize)
axes[0].set_ylabel(
    "Average absolute relative\nerror over time, $\\varepsilon$",
    fontsize=labelsize)
axes[0].set_xlabel("Number of model evaluations, $N_s$", fontsize=labelsize)
axes[0].set_yscale("log")
axes[0].set_xlim([0, 2000])
axes[0].legend(fontsize=fontsize, ncol=2)

grey = (0.5, 0.5, 0.5)
colors = get_current_colormap()
legend_elements = [
    Patch(facecolor=colors[0], label="PC"),
    Patch(facecolor=colors[1], label="QMC"),
    Line2D([0], [0], linewidth=0, label=""),
    Line2D([0], [0], color=grey, linewidth=linewidth, label="Mean"),
    Line2D([0], [0],
           color=grey,
           linewidth=linewidth,
           linestyle="--",
           label="Variance"),
    Line2D([0], [0],
           color=grey,
           linewidth=linewidth,
           linestyle=":",
           label="First-order Sobol")
]