Example #1
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()
Example #2
0
    def test_sankey(self):
        gplt.sankey(path=list_paths, projection=gcrs.PlateCarree(), edgecolor='white')

        gplt.sankey(path=list_paths, projection=gcrs.PlateCarree(), color='white')

        gplt.sankey(path=list_paths, projection=gcrs.PlateCarree(), linewidth=1)

        gplt.sankey(path=list_paths, projection=gcrs.PlateCarree(), linestyle='--')
Example #3
0
    def test_pointplot(self):
        try:
            gplt.pointplot(list_gaussian_points, projection=gcrs.PlateCarree(), color='white')

            gplt.pointplot(list_gaussian_points, projection=gcrs.PlateCarree(), s=5)

            gplt.pointplot(list_gaussian_points, projection=gcrs.PlateCarree(), legend_kwargs={'fancybox': False})
        finally: plt.close()
Example #4
0
    def test_aggplot(self):
        try:
            gplt.aggplot(dataframe_gaussian_points, hue='mock_category', projection=gcrs.PlateCarree())

            gplt.aggplot(dataframe_gaussian_points, hue='mock_category', by='mock_category',
                         projection=gcrs.PlateCarree())
        finally:
            plt.close()
Example #5
0
    def test_kdeplot(self):

        # Just four code paths.
        try:
            gplt.kdeplot(gaussian_points, projection=None, clip=None)
            gplt.kdeplot(gaussian_points, projection=None, clip=gaussian_polys)
            gplt.kdeplot(gaussian_points,
                         projection=gcrs.PlateCarree(),
                         clip=gaussian_polys)
            gplt.kdeplot(gaussian_points,
                         projection=gcrs.PlateCarree(),
                         clip=gaussian_polys)
        finally:
            plt.close()
Example #6
0
 def test_polyplot(self):
     try:
         gplt.polyplot(list_gaussian_polys,
                       projection=gcrs.PlateCarree(),
                       color='white')
     finally:
         plt.close()
Example #7
0
 def test_choropleth(self):
     try:
         gplt.choropleth(dataframe_gaussian_polys,
                         hue='hue_var',
                         projection=gcrs.PlateCarree(),
                         legend_kwargs={'fancybox': False})
     finally:
         plt.close()
Example #8
0
    def test_init_extent_geoaxes(self):
        """Test the extent setter code in the GeoAxes case."""
        # default, empty geometry case: set extent to default value of (0, 1)
        plot = Plot(self.gdf, **{**self.kwargs, **{'projection': gcrs.PlateCarree()}})
        assert plot.ax.get_xlim() == plot.ax.get_ylim() == (0, 1)

        # default, non-empty geometry case: use a (relaxed) geometry envelope
        plot = Plot(
            gpd.GeoDataFrame(geometry=[Point(-1, -1), Point(1, 1)]), 
            **{**self.kwargs, **{'projection': gcrs.PlateCarree()}}
        )
        xmin, xmax = plot.ax.get_xlim()
        ymin, ymax = plot.ax.get_ylim()
        assert xmin < -1
        assert xmax > 1
        assert ymin < -1
        assert ymax > 1

        # empty geometry, valid extent case: reuse prior extent, which is (0, 1) by default
        plot = Plot(self.gdf, **{
            **self.kwargs, **{'extent': (-1, -1, 1, 1), 'projection': gcrs.PlateCarree()}
        })
        assert plot.ax.get_xlim() == plot.ax.get_ylim() == (0, 1)

        # nonempty geometry, valid extent case: use extent
        plot = Plot(self.nonempty_gdf, **{
            **self.kwargs, **{'extent': (-1, -1, 1, 1), 'projection': gcrs.PlateCarree()}
        })
        xmin, xmax = plot.ax.get_xlim()
        ymin, ymax = plot.ax.get_ylim()
        assert xmin == -1
        assert xmax == 1
        assert ymin == -1
        assert ymax == 1

        # nonempty geometry, unsatisfiable extent case: warn and fall back to default
        with pytest.warns(UserWarning):
            # Orthographic can only show one half of the world at a time
            Plot(self.nonempty_gdf, **{
                **self.kwargs,
                **{'extent': (-180, -90, 180, 90), 'projection': gcrs.Orthographic()}
            })
Example #9
0
    def test_base_init(self):
        """Test the base init all plotters pass to Plot."""
        plot = Plot(self.gdf, **self.kwargs)
        assert plot.figsize == (8, 6)
        assert isinstance(plot.ax, SubplotBase)  # SO 11690597
        assert plot.extent == None
        assert plot.projection == None

        plot = Plot(self.gdf, **{**self.kwargs, **{'projection': gcrs.PlateCarree()}})
        assert plot.figsize == (8, 6)
        assert isinstance(plot.ax, GeoAxesSubplot)
        assert plot.extent == None
        assert isinstance(plot.projection, ccrs.PlateCarree)
Example #10
0
import pytest
import geoplot as gplt
import geoplot.crs as gcrs
import geopandas as gpd
import matplotlib.pyplot as plt
import warnings


@pytest.fixture(scope="module")
def countries():
    return gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))


@pytest.mark.mpl_image_compare
@pytest.mark.parametrize("proj", [
    gcrs.PlateCarree(),
    gcrs.LambertCylindrical(),
    gcrs.Mercator(),
    gcrs.Miller(),
    gcrs.Mollweide(),
    gcrs.Robinson(),
    gcrs.Sinusoidal(),
    pytest.param(gcrs.InterruptedGoodeHomolosine(), marks=pytest.mark.xfail),
    pytest.param(gcrs.Geostationary(), marks=pytest.mark.xfail),
    gcrs.NorthPolarStereo(),
    gcrs.SouthPolarStereo(),
    gcrs.Gnomonic(),
    gcrs.AlbersEqualArea(),
    gcrs.AzimuthalEquidistant(),
    gcrs.LambertConformal(),
    gcrs.Orthographic(),
Example #11
0
manhattan = manhattan.to_crs(epsg=4326)
manhattan = manhattan.reset_index(drop=True)
manhattan = manhattan.reset_index().rename(columns={'index': 'n'})

# Plot the data.

# This plot demonstrates an extremely useful trick. When used with a provided geometry, the aggplot plot type expects
# an iterable of geometries to be used for binning observations. The idea is that, in general, we have n observations
# and some smaller number k of locations containing them, and we will match observations within the same bin,
# average them in some way, and plot the result.
#
# Of course, what if n == k? In other words, what if every observation comes with its own location? In that case we
# can can pass those locations to the ``geometry`` parameter and pass the data's index to the ``by`` parameter,
# and ``aggplot`` will plot all of our records one at a time!
#
# This is a nice feature to have, and very useful for a wide variety of datasets. In this case we are plotting
# building ages in Manhattan using data taken from MapPLUTO
# (http://www1.nyc.gov/site/planning/data-maps/open-data/dwn-pluto-mappluto.page).
#
# Note that this plot is for the purposes of example only: it contains 40,000 geometries (far more than palatable)
# and so takes a long time to render. To explore the data for real take a look at this all-NYC webmap:
# http://pureinformation.net/building-age-nyc/.
ax = gplt.aggplot(manhattan,
                  projection=gcrs.PlateCarree(),
                  geometry=manhattan.geometry,
                  by=pd.Series(manhattan.index),
                  hue='YearBuilt',
                  linewidth=0)

ax.set_title("Buildings in Manhattan by Year Built")
plt.savefig("aggplot-singular.png", bbox_inches='tight', pad_inches=0.1)
Example #12
0
 def test_polyplot(self):
     gplt.polyplot(gaussian_polys, projection=None)
     gplt.polyplot(gaussian_polys, projection=gcrs.PlateCarree())
     plt.close()
Example #13
0
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import shapely
import numpy as np

# Define strategies.

# Static inputs.
gaussian_points = gplt.utils.gaussian_points(n=10)
gaussian_polys = gplt.utils.gaussian_polygons(
    gplt.utils.gaussian_points(n=100), n=2).append(
        gplt.utils.gaussian_multi_polygons(gplt.utils.gaussian_points(n=100),
                                           n=2))

# Projections.
projections = st.sampled_from((None, gcrs.PlateCarree()))

# Hue data.
schemes = st.sampled_from(
    (None, "equal_interval", "quantiles", "fisher_jenks"))
k = st.integers(min_value=4, max_value=9).map(lambda f: None if f == 4 else f)
datasets_numeric = st.lists(st.floats(allow_nan=False,
                                      allow_infinity=False,
                                      min_value=10**-10,
                                      max_value=10**10),
                            min_size=10,
                            max_size=10,
                            unique=True)
datasets_categorical = st.lists(st.text(st.characters(
    max_codepoint=1000, blacklist_categories=('Cc', 'Cs')),
                                        max_size=20),
Example #14
0
 def test_init_projection(self):
     """Test that passing a projection works as expected."""
     plot = Plot(self.gdf, **{
         **self.kwargs, 'projection': gcrs.PlateCarree()
     })
     assert isinstance(plot.projection, ccrs.PlateCarree)
Example #15
0
                       usecols="A:F")
    df = df.loc[df['Year'] == 2017]
    print(df.columns.values[-1], "column_names")
    df = df.rename(columns={df.columns.values[-1]: "Unbanked"})
    df = df.rename(columns={'Country': "name"})
    df['Unbanked'] = df.apply(take_inverse, axis=1)
    df = df.filter(items=['name', 'Unbanked'])
    df = df.reset_index(drop=True)
    df.to_csv("HeatMap.csv", sep='\t', encoding='utf-8')
    dfWorld = get_world_data_frame()
    print(df.columns.values, "columnNames")
    dfWorld = pd.merge(dfWorld, df, on=['name', 'name'])

    print(df.head())
    #proj = gcrs.AlbersEqualArea()
    proj = gcrs.PlateCarree()
    #ax = gplt.polyplot(dfWorld, projection=proj)
    #print(ax)
    legend_kwargs = {'loc': 'upper left'}
    #hue is the data series to visualize
    #dfWorld is geometry specified
    #proj is the projection type
    gplt.choropleth(
        dfWorld,
        hue=dfWorld['Unbanked'],  # Display data, passed as a Series
        projection=proj,
        cmap='Purples',
        k=None,  # Do not bin our counties.
        legend=True,
        edgecolor='white',
        linewidth=0.5,