def serialize_as_altair( topo_object, mesh=True, color=None, tooltip=True, projection="identity", objectname="data", geo_interface=False, ): import altair as alt # create a mesh visualization if geo_interface and mesh: # chart object chart = ( alt.Chart(topo_object, width=300) .mark_geoshape(filled=False) .project(type=projection, reflectY=True) ) # create a mesh visualization elif mesh and color is None: data = alt.InlineData( values=topo_object, format=alt.DataFormat(mesh=objectname, type="topojson") ) chart = ( alt.Chart(data, width=300) .mark_geoshape(filled=False) .project(type=projection, reflectY=True) ) # creating a chloropleth visualisation elif color is not None: data = alt.InlineData( values=topo_object, format=alt.DataFormat(feature=objectname, type="topojson"), ) if tooltip is True: tooltip = [color] chart = ( alt.Chart(data, width=300) .mark_geoshape() .encode( color=alt.Color(color, legend=alt.Legend(columns=2)), tooltip=tooltip ) .project(type=projection, reflectY=True) ) return chart
def geojson_feature(data, feature='features', **kwargs): """A convenience function for extracting features from a geojson object or url Parameters ---------- data : anyOf(string, geojson.GeoJSON) string is interpreted as URL from which to load the data set. geojson.GeoJSON is interpreted as data set itself. feature : string The JSON property containing the GeoJSON object set to convert to a GeoJSON feature collection. For example ``features[0].geometry``. \**kwargs : additional keywords passed to JsonDataFormat """ if isinstance(data, six.string_types): return alt.UrlData(url=data, format=alt.JsonDataFormat(type='json', property=feature, **kwargs)) elif hasattr(data, '__geo_interface__'): if isinstance(data, gpd.GeoDataFrame): data = alt.utils.sanitize_dataframe(data) return alt.InlineData(values=data.__geo_interface__, format=alt.JsonDataFormat(type='json', property=feature, **kwargs)) else: warnings.warn("data of type {0} not recognized".format(type(data))) return data
def convert_gfp_to_alt(gdf: geopandas.geodataframe) -> alt.InlineData: """ Converts a geopandas geoDataFrame into a Altair InlineData instance so it can be converted into a chart. Args: gdf (geopandas.geodataframe): Input geodataframe Returns: alt.InlineData: An instance of Altair's InlineData class. """ data = alt.InlineData( values=gdf.to_json(), # geopandas to geojson string # root object type is "FeatureCollection" but we need its features format=alt.DataFormat(property="features", type="json"), ) return data
def data_from_array(array): return alt.InlineData(array)
import json import geopandas as gpd import altair as alt import streamlit as st test = gpd.read_file('data/oakland/Oak_CityCouncilDistricts.shp') inline_data = alt.InlineData(format=alt.JsonDataFormat(property = 'features'), values=json.loads(test.to_json())) chart = alt.Chart(inline_data).mark_geoshape() st.vega_lite_chart(chart.to_dict())
def geography(self): return alt.InlineData( values=util.get_geojson_resource('municipalities.topojson'), format=alt.TopoDataFormat(type='topojson', feature='municipalities'))
corr = tracts_gdf_selected[var_demographic2].corr() corr.style.background_gradient(cmap='coolwarm') # It turns out that racial composition (pct_white) is substantially related to education level (pct_bachelor). It's surprisingly that mdeian household income is statistically associated with population, that is, tracts with larger number of population exhibit higher income level. # ### Spatial Patterns # In[34]: import altair as alt alt.renderers.enable('notebook') # In[44]: tracts_alt = alt.InlineData(values=tracts_gdf_selected.dropna().to_json(), format=alt.DataFormat(property='features', type='json')) alt.Chart(tracts_alt).mark_geoshape(stroke='population', ).properties( width=500, height=400, projection={ "type": 'mercator' }, ).encode(tooltip=['properties.population:Q', 'properties.NAME:N'], color='properties.population:Q') # In[45]: alt.Chart(tracts_alt).mark_geoshape(stroke='pct_male', ).properties( width=500,
change_fckng_polygons('Norway') countries = np.array([c['alpha3code'] for c in players.passportArea.values], dtype=np.object) # np.count_nonzero(~np.isnan(countries)) # countries.dtype pl_country = pd.DataFrame(data=countries, columns=['alpha3code']) type(pl_country) unique, counts = np.unique(pl_country, return_counts=True) bla = dict(zip(unique, counts)) europe['num_players'] = np.array( [bla[key] if key in bla else 0 for key in europe['iso_a3']]) # players.passportArea.values[:3] data = alt.InlineData( values=europe.__geo_interface__, # geopandas to geojson # root object type is "FeatureCollection" but we need its features format=alt.DataFormat(property='features', type='json')) selection = alt.selection_interval(bind='scales') # alt.data_transformers.enable('json') map = alt.Chart(data).mark_geoshape( # x=-150.2, # x2=-200, # y=-100, clip=True, stroke='black' ).encode( # color='properties.num_players:Q', # GeoDataFrame fields are accessible through a "properties" object # color=alt.Color('properties.num_players:Q', scale=alt.Scale(domain=[0, 500], range=['#ffffff', '#11efff'])), color=alt.Color('properties.num_players:Q', scale=alt.Scale(scheme='teals')),
color_continuous_scale=px.colors.sequential.Viridis, height=1200, ) fig.update_geos(fitbounds="locations", visible=False) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) fig fig.write_html("plotly_choropleth.html") # + # aug_df.crs = {"init": "epsg:27700"} # aug_df = aug_df.to_crs({"init": "epsg:4326"}) # define inline geojson data object data_geojson = alt.InlineData( values=aug_df.to_json(), format=alt.DataFormat(property="features", type="json") ) # chart object poverty_chart = ( alt.Chart(data_geojson) .mark_geoshape() .encode( color=alt.Color("properties.Taux de pauvreté:Q", legend=alt.Legend(columns=2),), tooltip=[ "properties.Délégation:N", "properties.Gouvernorat:N", "properties.Taux de pauvreté:Q", ], ) .properties(width=500, height=700)