Esempio n. 1
0
def geoplot(canvas):
    obesity = pd.read_csv(gplt.datasets.get_path("obesity_by_state"), sep="\t")
    contiguous_usa = gpd.read_file(gplt.datasets.get_path("contiguous_usa"))
    result = contiguous_usa.set_index("state").join(obesity.set_index("State"))
    # https://stackoverflow.com/a/51621986/6622587
    ax = canvas.figure.subplots(subplot_kw={"projection": gcrs.AlbersEqualArea()})
    gplt.cartogram(result, scale="Percent", projection=gcrs.AlbersEqualArea(), ax=ax)
Esempio n. 2
0
    def test_cartogram(self):
        try:
            gplt.cartogram(dataframe_gaussian_polys, scale='hue_var', projection=gcrs.PlateCarree(), facecolor='white')

            gplt.cartogram(dataframe_gaussian_polys, scale='hue_var',
                           projection=gcrs.PlateCarree(), legend_kwargs={'fancybox': False})
        finally:
            plt.close()
Esempio n. 3
0
    def test_cartogram(self):
        try:
            gplt.cartogram(dataframe_gaussian_polys, scale='hue_var', projection=gcrs.PlateCarree(), facecolor='white')

            gplt.cartogram(dataframe_gaussian_polys, scale='hue_var',
                           projection=gcrs.PlateCarree(), legend_kwargs={'fancybox': False})
        finally:
            plt.close()
Esempio n. 4
0
 def test_cartogram(self, projection, scale_dataset, hue_vars, legend_vars,
                    trace):
     kwargs = {
         'projection': projection,
         'scale': scale_dataset,
         'trace': trace
     }
     kwargs = {**kwargs, **hue_vars, **legend_vars}
     try:
         gplt.cartogram(gaussian_polys, **kwargs)
     finally:
         plt.close()
def create_cartogram(filename):
    """
    This function produces a cartogram map.
    """
    data_raw = gpd.read_file(filename)
    map = gplt.cartogram(data_raw,
                         projection=gcrs.Robinson(),
                         scale=data_raw['NUMPOINTS'],
                         hue=data_raw['NUMPOINTS'],
                         cmap='Reds',
                         k=5,
                         figsize=(30, 15)
                         )
    return map
Esempio n. 6
0
def main():
    data_dir = "./data/au-cities.csv"
    world = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))
    cities = gpd.read_file(gpd.datasets.get_path("naturalearth_cities"))

    print(world.head())
    ax = gp.polyplot(world, projection = gp.crs.Orthographic())
    ax.outline_patch.set_visible(True)

    #Graphs a choropleth of gdp / population
    gdp_per_person = world["gdp_md_est"] / world["pop_est"]
    scheme = mapclassify.Quantiles(gdp_per_person, k = 5)
    gp.choropleth(world, hue = gdp_per_person, scheme = scheme, 
    cmap = "Greens")
    print(world.head())

    #Graphs population size by establishing area size 
    #to the African continent
    africa = world[world.continent == "Africa"] 
    ax = gp.cartogram(africa, scale = "pop_est", limits = (0.2, 1), 
    edgecolor = "black")
    gp.polyplot(africa, edgecolor = "black", ax = ax)

    plt.show()
Esempio n. 7
0
    'Massachusetts', 'New Hampshire', 'Rhode Island', 'Vermont', 'Alabama',
    'Florida', 'Georgia', 'Mississippi', 'South Carolina', 'Illinois',
    'Indiana', 'Kentucky', 'North Carolina', 'Ohio', 'Tennessee', 'Virginia',
    'Wisconsin', 'West Virginia', 'Delaware', 'District of Columbia',
    'Maryland', 'New Jersey', 'New York', 'Pennsylvania', 'Maine', 'Michigan'
]
contiguous_usa['Obesity Rate'] = contiguous_usa['State'].map(
    lambda state: obesity.query("State == @state").iloc[0]['Percent'])

# Plot the data.
import geoplot as gplt
import geoplot.crs as gcrs
import matplotlib.pyplot as plt

ax = gplt.cartogram(contiguous_usa,
                    scale='Obesity Rate',
                    projection=gcrs.AlbersEqualArea(central_longitude=-98,
                                                    central_latitude=39.5),
                    limits=(0.75, 1),
                    linewidth=0.5,
                    hue='Obesity Rate',
                    cmap='Reds',
                    k=5,
                    trace_kwargs={'linewidth': 0.5},
                    legend=True,
                    legend_kwargs={'loc': 'lower right'},
                    legend_var='hue',
                    figsize=(12, 12))

plt.title("Adult Obesity Rate by State, 2013")
plt.savefig("obesity.png", bbox_inches='tight', pad_inches=0.1)
# you want to use color as a visual variable, specify a ``choropleth``. Here
# we sort GDP per person by country into five buckets by color.

geoplot.choropleth(world,
                   hue=world['gdp_md_est'] / world['pop_est'],
                   cmap='Greens',
                   figsize=(8, 4))

###############################################################################
# If you want to use size as a visual variable, use a ``cartogram``. Here are
# population estimates for countries in Africa.

africa = world.query('continent == "Africa"')
ax = geoplot.cartogram(africa,
                       scale='pop_est',
                       limits=(0.2, 1),
                       edgecolor='None',
                       figsize=(7, 8))
geoplot.polyplot(africa, edgecolor='gray', ax=ax)

###############################################################################
# If we have data in the shape of points in space, we may generate a
# three-dimensional heatmap on it using ``kdeplot``.

ax = geoplot.kdeplot(collisions,
                     clip=boroughs.geometry,
                     shade=True,
                     cmap='Reds',
                     projection=geoplot.crs.AlbersEqualArea())
geoplot.polyplot(boroughs, ax=ax, zorder=1)
Esempio n. 9
0
def geospatial_viz(geo_data_url,
                   point_data_url=None,
                   att_var=None,
                   map_type=None):
    '''
    function to visualize the attribute information in map. (eg, population in states)
    geo_att_data: geodataframe that contains both geometry and attributes info
    att_var: the attributes to be visualized in the map
    map_type: string, the type of map to be viz. pointplot, choropleth, voronoi
    
    if point_data = None, att_var must be from geo_data
    
    '''
    geo_data = gpd.read_file(geo_data_url)
    print(geo_data.head())

    if point_data_url == 'No point attribute data':
        if att_var is None:
            ax = gplt.polyplot(geo_data, figsize=(10, 5))
            ax.set_title('plain map of continental USA', fontsize=16)
        else:
            if map_type == 'choropleth':
                scheme = mc.FisherJenks(geo_data[att_var], k=5)
                labels = scheme.get_legend_classes()
                ax = gplt.polyplot(geo_data, projection=gcrs.AlbersEqualArea())
                gplt.choropleth(geo_data,
                                hue=att_var,
                                edgecolor='white',
                                linewidth=1,
                                cmap='Blues',
                                legend=True,
                                scheme=scheme,
                                legend_labels=labels,
                                ax=ax)
                ax.set_title('{} in the continental US'.format(att_var),
                             fontsize=16)

            if map_type == "cartogram":
                gplt.cartogram(geo_data,
                               scale=att_var,
                               edgecolor='black',
                               projection=gcrs.AlbersEqualArea())

    else:
        point_data = gpd.read_file(point_data_url)
        scheme = mc.Quantiles(point_data[att_var], k=5)
        labels = scheme.get_legend_classes()

        if map_type == 'pointplot':
            if isinstance(point_data.geometry[0],
                          shapely.geometry.point.Point):
                ax = gplt.polyplot(geo_data,
                                   edgecolor='white',
                                   facecolor='lightgray',
                                   figsize=(12, 8)
                                   #projection = gcrs.AlbersEqualArea()
                                   )
                gplt.pointplot(point_data,
                               ax=ax,
                               hue=att_var,
                               cmap='Blues',
                               scheme=scheme,
                               scale=att_var,
                               legend=True,
                               legend_var='scale',
                               legend_kwargs={"loc": 'lower right'},
                               legend_labels=labels)
                ax.set_title(
                    'Cities in the continental US, by population 2010',
                    fontsize=16)
            else:
                print('Geometry data type not valid')

        if map_type == "voronoi":
            # check uniqueness of coordinates
            duplicates = point_data.geometry.duplicated()
            point_data_unique = point_data[-duplicates]
            proj = gplt.crs.AlbersEqualArea(central_longitude=-98,
                                            central_latitude=39.5)

            ax = gplt.voronoi(point_data_unique,
                              hue=att_var,
                              clip=geo_data,
                              projection=proj,
                              cmap='Blues',
                              legend=True,
                              edgecolor="white",
                              linewidth=0.01)

            gplt.polyplot(geo_data,
                          ax=ax,
                          extent=geo_data.total_bounds,
                          edgecolor="black",
                          linewidth=1,
                          zorder=1)
            plt.title("{} in US cities".format(att_var), fontsize=16)
Esempio n. 10
0
ax.set_global()
ax.outline_patch.set_visible(True)

###############################################################################
# ``polyplot`` is trivial and can only plot the geometries you pass to it. If
# you want to use color as a visual variable, specify a ``choropleth``. Here
# we sort GDP per person by country into five buckets by color.

geoplot.choropleth(df, hue='gdp_pp', cmap='Greens', figsize=(8, 4))

###############################################################################
# If you want to use size as a visual variable, you want a ``cartogram``. Here
# are population estimates for countries in Africa.

geoplot.cartogram(df[df['continent'] == 'Africa'],
                  scale='pop_est',
                  limits=(0.2, 1),
                  figsize=(7, 8))

###############################################################################
# If we have data in the shape of points in space, we may generate a
# three-dimensional heatmap on it using ``kdeplot``. This example also
# demonstrates how easy it is to stack plots on top of one another.

ax = geoplot.kdeplot(injurious_collisions.sample(1000),
                     shade=True,
                     shade_lowest=False,
                     clip=boroughs.geometry)
geoplot.polyplot(boroughs, ax=ax)

###############################################################################
# Alternatively, we may partition the space into neighborhoods automatically,
Esempio n. 11
0
geomap = geomap.drop(['cartodb_id', 'regiao', 'nome_uf', 'geocodigo', 'simounao'],
                      axis=1)

# Order Columns
geomap = geomap[['uf_05', 'População', 'Médicos', 'geometry']]

# Rename Columns
geomap.columns = ['UF', 'População', 'Médicos', 'geometry']

import geoplot
import geoplot.crs as gcrs

# Plot cartogram
geoplot.cartogram(geomap, 
                  scale='População',
                  hue='Médicos', 
                  k=None, 
                  cmap='coolwarm')

# Add Labels
plt.title('População por Médicos')
plt.legend()
plt.xticks([])
plt.yticks([])

# Save file
plt.savefig(path + 'cartogram.png', dpi=600)

# Show the plot
plt.show()
import pandas as pd
import matplotlib.pyplot as plt

df_map = GeoDataFrame.from_file('Virtual_Map1.shp')
df_city=pd.read_csv("Virtual_City.csv") 
 
df=pd.merge(right=df_map, left=df_city,how='right',on="country")
df=GeoDataFrame(df)

#----------------------------------orange----------------------------------------------------
ax = geoplot.cartogram(
    df,
    scale='orange', limits=(0.5, 0.9),
    #projection=gcrs.AlbersEqualArea(central_longitude=-98, central_latitude=39.5),
    hue='orange', cmap='Reds', k=10,
    linewidth=0.5,
    legend=True, legend_kwargs={'loc': 'center',
                                'bbox_to_anchor':(1.15, 0, 0, 1),
                                'title':'value',
                                'edgecolor':'white'}, legend_var='hue',
    figsize=(5, 5)
)
geoplot.polyplot(df, facecolor='lightgray', edgecolor='white', ax=ax)

#plt.title("Adult Obesity Rate by State, 2013")
#plt.savefig("cartogram_orange.pdf",bbox_inches='tight', pad_inches=0.1)

#-----------------------------------apple---------------------------------------------------
ax = geoplot.cartogram(
    df,
    scale='apple', limits=(0.5, 0.9),
    #projection=gcrs.AlbersEqualArea(central_longitude=-98, central_latitude=39.5),
Esempio n. 13
0
    def test_cartogram(self):
        try:
            gplt.cartogram(series_gaussian_polys, scale=list_hue_values)
            gplt.cartogram(dataframe_gaussian_polys, scale=list_hue_values)

            gplt.cartogram(dataframe_gaussian_polys, hue=list_hue_values, scale=list_hue_values)
            gplt.cartogram(dataframe_gaussian_polys, hue=series_hue_values, scale=list_hue_values)
            gplt.cartogram(dataframe_gaussian_polys, hue=map_hue_values(), scale=list_hue_values)
            gplt.cartogram(dataframe_gaussian_polys, hue='hue_var', scale=list_hue_values)
        finally:
            plt.close('all')
Esempio n. 14
0
#border
border = gplt.polyplot(
    df=covidMap,
    projection=gcrs.Mercator(),  #reproject
    edgecolor='gray',  #border
    facecolor='gainsboro')  #fill of polygon
#area and color
gplt.cartogram(
    df=covidMap,  #map
    scheme=mc.EqualInterval(covidMap.DeathsPer100k, k=3),
    cmap=plt.get_cmap('YlGnBu', 3),  #palette
    hue="DeathsPer100k",  #var for color                   
    scale='CasesPer100k',  #var for resize
    limits=(0.3, 1),  #limits cartogram polygons       
    edgecolor='None',  #no border
    legend=True,
    legend_var='hue',  #legend of what
    legend_kwargs={
        'bbox_to_anchor': (0.1, 0.4),  #location
        'frameon': True,  #with frame?
        'markeredgecolor': 'k',
        'title': "DeathsPer100k"
    },
    ax=border)
#%%
# mapOfPoints

import geoplot.crs as gcrs  #activating!

#borders
countyBorders = gplt.polyplot(
Esempio n. 15
0
    data_cases_cleaned_day = data_cases_cleaned_day.fillna(0)
    # print(data_cases_cleaned_day)
    contiguous_usa['cases'] = contiguous_usa['state'].map(get_cases)

    contiguous_usa['deaths'] = contiguous_usa['state'].map(get_deaths)

    m, n = i % 2, i // 2
    try:
        ax = gplt.cartogram(
            contiguous_usa,
            scale='cases',
            projection=gcrs.AlbersEqualArea(central_longitude=-98,
                                            central_latitude=39.5),
            hue='deaths',
            cmap='YlOrRd',
            #norm=colors.Normalize(vmin=0, vmax=18000),
            scheme=scheme,
            linewidth=0.5,
            legend=True,
            legend_kwargs={'loc': 'lower right'},
            legend_var='hue',
            figsize=(16, 20),
            # ax = axes[m][n]
        )
        gplt.polyplot(contiguous_usa,
                      facecolor='lightgray',
                      edgecolor='None',
                      ax=ax)
    except:
        pass

    plt.title(
Esempio n. 16
0
import geopandas as gpd
from quilt.data.ResidentMario import geoplot_data

obesity = geoplot_data.obesity_by_state()
contiguous_usa = gpd.read_file(geoplot_data.contiguous_usa())
contiguous_usa['Obesity Rate'] = contiguous_usa['State'].map(
    lambda state: obesity.query("State == @state").iloc[0]['Percent']
)


# Plot the data.
import geoplot as gplt
import geoplot.crs as gcrs
import matplotlib.pyplot as plt


ax = gplt.cartogram(contiguous_usa, scale='Obesity Rate',
                    projection=gcrs.AlbersEqualArea(central_longitude=-98, central_latitude=39.5),
                    limits=(0.75, 1),
                    linewidth=0.5,
                    hue='Obesity Rate',
                    cmap='Reds',
                    k=5,
                    trace_kwargs={'linewidth': 0.5},
                    legend=True,
                    legend_kwargs={'loc': 'lower right'},
                    legend_var='hue',
                    figsize=(12, 12))

plt.title("Adult Obesity Rate by State, 2013")
plt.savefig("obesity.png", bbox_inches='tight', pad_inches=0.1)
Esempio n. 17
0
ax = geoplot.polyplot(df, projection=gcrs.Orthographic(), figsize=(8, 4))
ax.set_global()
ax.outline_patch.set_visible(True)

###############################################################################
# ``polyplot`` is trivial and can only plot the geometries you pass to it. If
# you want to use color as a visual variable, specify a ``choropleth``. Here
# we sort GDP per person by country into five buckets by color.

geoplot.choropleth(df, hue='gdp_pp', cmap='Greens', figsize=(8, 4))

###############################################################################
# If you want to use size as a visual variable, you want a ``cartogram``. Here
# are population estimates for countries in Africa.

geoplot.cartogram(df[df['continent'] == 'Africa'],
                  scale='pop_est', limits=(0.2, 1), figsize=(7, 8))

###############################################################################
# If we have data in the shape of points in space, we may generate a
# three-dimensional heatmap on it using ``kdeplot``. This example also
# demonstrates how easy it is to stack plots on top of one another.

ax = geoplot.kdeplot(injurious_collisions.sample(1000),
                     shade=True, shade_lowest=False,
                     clip=boroughs.geometry)
geoplot.polyplot(boroughs, ax=ax)

###############################################################################
# Alternatively, we may partition the space into neighborhoods automatically,
# using Voronoi tessellation.
Esempio n. 18
0
# Shape the data.
obesity = pd.read_csv("../../data/obesity/obesity_by_state.tsv", sep='\t')
usa = gpd.read_file("../../data/united_states/usa.geojson")
continental_usa = usa[~usa['adm1_code'].isin(['USA-3517', 'USA-3563'])]
continental_usa['State'] = [
    'Minnesota', 'Montana', 'North Dakota', 'Idaho', 'Washington', 'Arizona',
    'California', 'Colorado', 'Nevada', 'New Mexico', 'Oregon', 'Utah',
    'Wyoming', 'Arkansas', 'Iowa', 'Kansas', 'Missouri', 'Nebraska',
    'Oklahoma', 'South Dakota', 'Louisiana', 'Texas', 'Connecticut',
    'Massachusetts', 'New Hampshire', 'Rhode Island', 'Vermont', 'Alabama',
    'Florida', 'Georgia', 'Mississippi', 'South Carolina', 'Illinois',
    'Indiana', 'Kentucky', 'North Carolina', 'Ohio', 'Tennessee', 'Virginia',
    'Wisconsin', 'West Virginia', 'Delaware', 'District of Columbia',
    'Maryland', 'New Jersey', 'New York', 'Pennsylvania', 'Maine', 'Michigan'
]
continental_usa['Obesity Rate'] = continental_usa['State'].map(
    lambda state: obesity.query("State == @state").iloc[0]['Percent'])

# Plot the data.
ax = gplt.cartogram(continental_usa,
                    scale='Obesity Rate',
                    projection=gcrs.AlbersEqualArea(central_longitude=-98,
                                                    central_latitude=39.5),
                    limits=(0.75, 1),
                    linewidth=0.5,
                    facecolor='steelblue',
                    trace_kwargs={'linewidth': 0.5})
ax.set_ylim((-1597757.3894385984, 1457718.4893930717))
plt.title("Adult Obesity Rate by State, 2013")
plt.savefig("obesity.png", bbox_inches='tight', pad_inches=0.1)
Esempio n. 19
0
    def test_cartogram(self):
        try:
            gplt.cartogram(series_gaussian_polys, scale=list_hue_values)
            gplt.cartogram(dataframe_gaussian_polys, scale=list_hue_values)

            gplt.cartogram(dataframe_gaussian_polys,
                           hue=list_hue_values,
                           scale=list_hue_values)
            gplt.cartogram(dataframe_gaussian_polys,
                           hue=series_hue_values,
                           scale=list_hue_values)
            gplt.cartogram(dataframe_gaussian_polys,
                           hue=map_hue_values(),
                           scale=list_hue_values)
            gplt.cartogram(dataframe_gaussian_polys,
                           hue='hue_var',
                           scale=list_hue_values)
        finally:
            plt.close('all')
Esempio n. 20
0
    print(i + 1, float(frac))

wien['street'] = wien.BEZNR.map(district_dict)**(1 / 2)

# %%


def identity_scale(minval, maxval):
    def scalar(val):
        return val

    return scalar


f, ax = plt.subplots(1, figsize=(20, 20))
geoplot.polyplot(wien, ax=ax, color='green', alpha=0.1)
ax = geoplot.cartogram(wien,
                       scale='street',
                       scale_func=identity_scale,
                       limits=(0, 1),
                       edgecolor='None',
                       figsize=(7, 8),
                       ax=ax,
                       color='black',
                       alpha=0.7)
geoplot.polyplot(wien, edgecolor='gray', ax=ax)

list(wien)

# %%