Esempio n. 1
0
def plot_MDS(Data, cmap="viridis"):
    Fmax = max(Data.log_den)
    Rho_bord_m = np.copy(Data.log_den_bord)
    d_dis = np.zeros((Data.N_clusters, Data.N_clusters), dtype=float)
    model = manifold.MDS(n_components=2,
                         n_jobs=None,
                         dissimilarity="precomputed")
    for i in range(Data.N_clusters):
        for j in range(Data.N_clusters):
            d_dis[i][j] = Fmax - Rho_bord_m[i][j]
    for i in range(Data.N_clusters):
        d_dis[i][i] = 0.0
    out = model.fit_transform(d_dis)
    fig, ax = plt.subplots(nrows=1, ncols=1)
    s = []
    col = []
    for i in range(Data.N_clusters):
        s.append(20.0 * np.sqrt(len(Data.cluster_indices[i])))
        col.append(i)
    plt.scatter(out[:, 0], out[:, 1], s=s, c=col, cmap=cmap)
    cmal = cm.get_cmap(cmap, Data.N_clusters)
    colors = cmal(np.arange(0, cmal.N))
    for i in range(Data.N_clusters):
        cc = "k"
        r = colors[i][0]
        g = colors[i][1]
        b = colors[i][2]
        luma = (0.2126 * r + 0.7152 * g + 0.0722 * b) * 255
        if luma < 156:
            cc = "w"
        plt.annotate(
            i,
            (out[i, 0], out[i, 1]),
            horizontalalignment="center",
            verticalalignment="center",
            c=cc,
            weight="bold",
        )
    #    for i in range(Data.N_clusters):
    #        ax.annotate(i, (out[i, 0], out[i, 1]))
    # Add edges
    rr = np.amax(Rho_bord_m)
    if rr > 0.0:
        Rho_bord_m = Rho_bord_m / rr * 100.0
    start_idx, end_idx = np.where(out)
    segments = [[out[i, :], out[j, :]] for i in range(len(out))
                for j in range(len(out))]
    values = np.abs(Rho_bord_m)
    lc = LineCollection(segments,
                        zorder=0,
                        norm=plt.Normalize(0, values.max()))
    lc.set_array(Rho_bord_m.flatten())
    # lc.set_linewidths(np.full(len(segments),0.5))
    lc.set_edgecolor(np.full(len(segments), "black"))
    lc.set_facecolor(np.full(len(segments), "black"))
    lc.set_linewidths(0.02 * Rho_bord_m.flatten())
    ax.add_collection(lc)
    # fig.savefig('2D.png')
    plt.show()
Esempio n. 2
0
def plot_map(year, disease, color_parameter, std_num_records):
    mpl.rcParams['font.size'] = 10.
    mpl.rcParams['font.family'] = 'Comic Sans MS'
    mpl.rcParams['axes.labelsize'] = 8.
    mpl.rcParams['xtick.labelsize'] = 6.
    mpl.rcParams['ytick.labelsize'] = 6.
    fig = plt.figure(figsize=(11.7, 8.3))
    plt.style.use('fivethirtyeight')
    plt.subplots_adjust(left=0.05,
                        right=0.95,
                        top=0.90,
                        bottom=0.05,
                        wspace=0.15,
                        hspace=0.05)
    ax = plt.subplot(111)
    m = Basemap(resolution='i',
                projection='merc',
                llcrnrlon=-132,
                llcrnrlat=22,
                urcrnrlon=-60,
                urcrnrlat=50)
    m.etopo()
    m.drawcountries()
    for record, shape, num in zip(records, shapes, std_num_records):
        lons, lats = zip(*shape.points)
        data = np.array(m(lons, lats)).T

        if len(shape.parts) == 1:
            segs = [
                data,
            ]
        else:
            segs = []
            for i in range(1, len(shape.parts)):
                index = shape.parts[i - 1]
                index2 = shape.parts[i]
                segs.append(data[index:index2])
            segs.append(data[index2:])

        lines = LineCollection(segs, antialiaseds=(1, ))
        color = colors.hsv_to_rgb((color_parameter, num, 1))
        lines.set_facecolor(color)
        lines.set_edgecolors('k')
        lines.set_linewidth(0.1)
        ax.add_collection(lines)
    m.drawstates(linewidth=0.5)
    m.drawcoastlines(linewidth=0.5)
    plt.title('geo-heatmap for {} in {}'.format(disease, year))

    plt.savefig('geo-heatmap for {} in {}.pdf'.format(disease, year))
Esempio n. 3
0
def generate_boundary_artist(vertices, color):
    if DIM == 2:
        artist = LineCollection(vertices)
        artist.set_color(color)
        artist.set_linewidth(2.5)
    elif DIM == 3:
        artist = Poly3DCollection(vertices, linewidths=1)
        # transparency alpha must be set BEFORE face/edge color
        artist.set_alpha(0.5)
        artist.set_facecolor(color)
        artist.set_edgecolor('k')
    else:
        raise ValueError(
            "%d dimensions needs special attention for plotting." % int(DIM))
    return artist
Esempio n. 4
0
def generate_boundary_artist(vertices, color):
    ndim = len(next(iter(vertices[0])))
    vertices = tuple(map(tuple, vertices))
    if ndim == 2:
        artist = LineCollection(vertices)
        artist.set_color(color)
        artist.set_linewidth(2.5)
    elif ndim == 3:
        artist = Poly3DCollection(vertices, linewidth=1)
        # transparency alpha must be set BEFORE face/edge color
        artist.set_alpha(0.5)
        artist.set_facecolor(color)
        artist.set_edgecolor('k')
    else:
        raise ValueError("{:d} dimensions needs special attention for plotting".format(ndim))
    return artist
Esempio n. 5
0
def plot_MDS(Data):
    Fmax = max(Data.Rho)
    Rho_bord_m = np.copy(Data.out_bord)
    d_dis = np.zeros((Data.Nclus_m, Data.Nclus_m), dtype=float)
    model = manifold.MDS(n_components=2,
                         n_jobs=None,
                         dissimilarity='precomputed')
    for i in range(Data.Nclus_m):
        for j in range(Data.Nclus_m):
            d_dis[i][j] = Fmax - Rho_bord_m[i][j]
    for i in range(Data.Nclus_m):
        d_dis[i][i] = 0.
    out = model.fit_transform(d_dis)
    fig, ax = plt.subplots(nrows=1, ncols=1)
    s = []
    col = []
    for i in range(Data.Nclus_m):
        s.append(20. * np.sqrt(len(Data.clstruct_m[i])))
        col.append(i)
    plt.scatter(out[:, 0], out[:, 1], s=s, c=col)
    for i in range(Data.Nclus_m):
        ax.annotate(i, (out[i, 0], out[i, 1]))
    # Add edges
    rr = np.amax(Rho_bord_m)
    if (rr > 0.):
        Rho_bord_m = Rho_bord_m / rr * 100.
    start_idx, end_idx = np.where(out)
    segments = [[out[i, :], out[j, :]] for i in range(len(out))
                for j in range(len(out))]
    values = np.abs(Rho_bord_m)
    lc = LineCollection(segments,
                        zorder=0,
                        norm=plt.Normalize(0, values.max()))
    lc.set_array(Rho_bord_m.flatten())
    # lc.set_linewidths(np.full(len(segments),0.5))
    lc.set_edgecolor(np.full(len(segments), 'black'))
    lc.set_facecolor(np.full(len(segments), 'black'))
    lc.set_linewidths(0.02 * Rho_bord_m.flatten())
    ax.add_collection(lc)
    #fig.savefig('2D.png')
    plt.show()
Esempio n. 6
0
def plot_europe_map(country_weights, b=None, ax=None):
    """
    Plot a map from shapefiles with coutnries colored by gamma. Inspired by Magnus.
    """
    if ax == None:
        ax = plt.subplot(111)
    m = Basemap(llcrnrlon=-10., llcrnrlat=30., urcrnrlon=50., urcrnrlat=72.,
                projection='lcc', lat_1=40., lat_2=60., lon_0=20.,
                resolution='l', area_thresh=1000.,
                rsphere=(6378137.00, 6356752.3142))
    m.drawcoastlines(linewidth=0)
    r = shapefile.Reader(r'settings/ne_10m_admin_0_countries/ne_10m_admin_0_countries')
    all_shapes = r.shapes()
    all_records = r.records()
    shapes = []
    records = []
    for country in all_countries:
        shapes.append(all_shapes[shapefile_index[country]])
        records.append(all_records[shapefile_index[country]])

    country_count = 0
    for record, shape in zip(records, shapes):
        lons, lats = zip(*shape.points)
        data = np.array(m(lons, lats)).T
        if len(shape.parts) == 1:
            segs = [data, ]
        else:
            segs = []
            for i in range(1, len(shape.parts)):
                index = shape.parts[i - 1]
                index2 = shape.parts[i]
                segs.append(data[index:index2])
            segs.append(data[index2:])
        lines = LineCollection(segs, antialiaseds=(1,))
        lines.set_facecolor(cmap(country_weights[country_count]))
        lines.set_edgecolors('k')
        lines.set_linewidth(0.3)
        ax.add_collection(lines)
        country_count += 1
    if b: plt.text(1.5e5, 4e6, r'$\beta = ' + str(b) + r'$', fontsize=12)
Esempio n. 7
0
def plot_linestring_collection(ax,
                               geoms,
                               colors_or_values,
                               plot_values,
                               vmin=None,
                               vmax=None,
                               cmap=None,
                               linewidth=1.0,
                               **kwargs):
    """
    Plots a collection of LineString and MultiLineString geometries to `ax`

    Parameters
    ----------

    ax : matplotlib.axes.Axes
        where shapes will be plotted

    geoms : a sequence of `N` LineStrings and/or MultiLineStrings (can be mixed)

    colors_or_values : a sequence of `N` values or RGBA tuples
        It should have 1:1 correspondence with the geometries (not their components).

    plot_values : bool
        If True, `colors_or_values` is interpreted as a list of values, and will
        be mapped to colors using vmin/vmax/cmap (which become required).
        Otherwise `colors_or_values` is interpreted as a list of colors.

    Returns
    -------

    collection : matplotlib.collections.Collection that was plotted
    """

    from matplotlib.collections import LineCollection

    components, component_colors_or_values = _flatten_multi_geoms(
        geoms, colors_or_values)

    # LineCollection does not accept some kwargs.
    if 'markersize' in kwargs:
        del kwargs['markersize']
    segments = [np.array(linestring)[:, :2] for linestring in components]
    collection = LineCollection(segments, linewidth=linewidth, **kwargs)

    if plot_values:
        collection.set_array(np.array(component_colors_or_values))
        collection.set_cmap(cmap)
        collection.set_clim(vmin, vmax)
    else:
        # set_color magically sets the correct combination of facecolor and
        # edgecolor, based on collection type.
        collection.set_color(component_colors_or_values)

        # If the user set facecolor and/or edgecolor explicitly, the previous
        # call to set_color might have overridden it (remember, the 'color' may
        # have come from plot_series, not from the user). The user should be
        # able to override matplotlib's default behavior, by setting them again
        # after set_color.
        if 'facecolor' in kwargs:
            collection.set_facecolor(kwargs['facecolor'])

        if 'edgecolor' in kwargs:
            collection.set_edgecolor(kwargs['edgecolor'])

    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    return collection
Esempio n. 8
0
def plots_topography(dpa, ax_dendrogram, ax_project):
    Nclus_m = np.max(dpa.labels_) + 1
    cmap = plt.get_cmap('tab10', Nclus_m)
    # Convert from border densities to distances
    nd = int((Nclus_m * Nclus_m - Nclus_m) / 2)
    Dis = np.empty(nd, dtype=float)
    nl = 0
    Fmax = max(dpa.densities_)
    Rho_bord = np.zeros((Nclus_m, Nclus_m), dtype=float)
    for row in dpa.topography_:
        Rho_bord[row[0]][row[1]] = row[2]
        Rho_bord[row[1]][row[0]] = row[2]
        Dis[nl] = Fmax - row[2]
        nl = nl + 1
    # dendrogram representation
    DD = sp.cluster.hierarchy.single(Dis)
    dn = sp.cluster.hierarchy.dendrogram(DD,
                                         color_threshold=0,
                                         above_threshold_color='k',
                                         ax=ax_dendrogram)
    xlbls = ax_dendrogram.get_xmajorticklabels()
    dorder = []
    for lbl in xlbls:
        dorder.append(int(lbl._text))
        lbl.set_color(cmap(int(lbl._text)))
        lbl.set_weight('bold')


# 2D projection representation of the topography
    pop = np.zeros((Nclus_m), dtype=int)
    for i in range(len(dpa.labels_)):
        pop[dpa.labels_[i]] = pop[dpa.labels_[i]] + 1
    d_dis = np.zeros((Nclus_m, Nclus_m), dtype=float)
    model = manifold.MDS(n_components=2,
                         n_jobs=10,
                         dissimilarity='precomputed')
    for i in range(Nclus_m):
        for j in range(Nclus_m):
            d_dis[i][j] = Fmax - Rho_bord[i][j]
    for i in range(Nclus_m):
        d_dis[i][i] = 0.
    out = model.fit_transform(d_dis)
    ax_project.yaxis.set_major_locator(plt.NullLocator())
    ax_project.xaxis.set_major_locator(plt.NullLocator())
    s = []
    col = []
    for i in range(Nclus_m):
        s.append(20. * sqrt(pop[i]))
        col.append(i)
    ax_project.scatter(out[:, 0], out[:, 1], s=s, c=col, cmap=cmap)
    #plt.colorbar(ticks=range(Nclus_m))
    #plt.clim(-0.5, Nclus_m-0.5)
    for i in range(Nclus_m):
        ax_project.annotate(i, (out[i, 0], out[i, 1]))
    for i in range(Nclus_m):
        for j in range(Nclus_m):
            d_dis[i][j] = Rho_bord[i][j]
    rr = np.amax(d_dis)
    if (rr > 0.):
        d_dis = d_dis / rr * 100.
    start_idx, end_idx = np.where(out)
    segments = [[out[i, :], out[j, :]] for i in range(len(out))
                for j in range(len(out))]
    values = np.abs(d_dis)
    lc = LineCollection(segments,
                        zorder=0,
                        norm=plt.Normalize(0, values.max()))
    lc.set_array(d_dis.flatten())
    lc.set_edgecolor(np.full(len(segments), 'black'))
    lc.set_facecolor(np.full(len(segments), 'black'))
    lc.set_linewidths(0.2 * Rho_bord.flatten())
    ax_project.add_collection(lc)
    return ax_dendrogram, ax_project
Esempio n. 9
0
def plot_linestring_collection(ax, geoms, colors_or_values, plot_values,
                               vmin=None, vmax=None, cmap=None,
                               linewidth=1.0, **kwargs):
    """
    Plots a collection of LineString and MultiLineString geometries to `ax`

    Parameters
    ----------

    ax : matplotlib.axes.Axes
        where shapes will be plotted

    geoms : a sequence of `N` LineStrings and/or MultiLineStrings (can be mixed)

    colors_or_values : a sequence of `N` values or RGBA tuples
        It should have 1:1 correspondence with the geometries (not their components).

    plot_values : bool
        If True, `colors_or_values` is interpreted as a list of values, and will
        be mapped to colors using vmin/vmax/cmap (which become required).
        Otherwise `colors_or_values` is interpreted as a list of colors.

    Returns
    -------

    collection : matplotlib.collections.Collection that was plotted
    """

    from matplotlib.collections import LineCollection

    components, component_colors_or_values = _flatten_multi_geoms(
        geoms, colors_or_values)

    # LineCollection does not accept some kwargs.
    if 'markersize' in kwargs:
        del kwargs['markersize']
    segments = [np.array(linestring)[:, :2] for linestring in components]
    collection = LineCollection(segments,
                                linewidth=linewidth, **kwargs)

    if plot_values:
        collection.set_array(np.array(component_colors_or_values))
        collection.set_cmap(cmap)
        collection.set_clim(vmin, vmax)
    else:
        # set_color magically sets the correct combination of facecolor and
        # edgecolor, based on collection type.
        collection.set_color(component_colors_or_values)

        # If the user set facecolor and/or edgecolor explicitly, the previous
        # call to set_color might have overridden it (remember, the 'color' may
        # have come from plot_series, not from the user). The user should be
        # able to override matplotlib's default behavior, by setting them again
        # after set_color.
        if 'facecolor' in kwargs:
            collection.set_facecolor(kwargs['facecolor'])

        if 'edgecolor' in kwargs:
            collection.set_edgecolor(kwargs['edgecolor'])

    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    return collection