kunifujiwara commited on
Commit
419ed50
β€’
1 Parent(s): 8f75bb5

modify pages

Browse files
pages/2_🌲_Japan_Vegetation_Cover.py CHANGED
@@ -12,25 +12,6 @@ import matplotlib.pyplot as plt
12
 
13
  st.set_page_config(layout="wide")
14
 
15
- st.sidebar.info(
16
- """
17
- - Web App URL: <https://streamlit.gishub.org>
18
- - GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
19
- """
20
- )
21
-
22
- st.sidebar.title("Contact")
23
- st.sidebar.info(
24
- """
25
- Qiusheng Wu at [wetlands.io](https://wetlands.io) | [GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
26
- """
27
- )
28
-
29
- STREAMLIT_STATIC_PATH = pathlib.Path(st.__path__[0]) / "static"
30
- DOWNLOADS_PATH = STREAMLIT_STATIC_PATH / "downloads"
31
- if not DOWNLOADS_PATH.is_dir():
32
- DOWNLOADS_PATH.mkdir()
33
-
34
  # Data source
35
  data_links = {
36
  "Tokyo": "https://raw.githubusercontent.com/kunifujiwara/data/master/frac_veg/FRAC_VEG_Tokyo.geojson",
@@ -47,17 +28,7 @@ def get_geom_data(prefecture):
47
  response = requests.get(data_links[prefecture])
48
  if response.status_code == 200:
49
  geojson_data = json.loads(response.content)
50
- features = geojson_data['features']
51
-
52
- data = []
53
- for feature in features:
54
- properties = feature['properties']
55
- geometry = shape(feature['geometry'])
56
- properties['geometry'] = geometry
57
- data.append(properties)
58
-
59
- gdf = gpd.GeoDataFrame(data)
60
- gdf.set_geometry('geometry', inplace=True)
61
  return gdf
62
  else:
63
  st.error(f"Failed to fetch data for {prefecture}. Status code: {response.status_code}")
@@ -66,19 +37,10 @@ def get_geom_data(prefecture):
66
  def get_data_columns(gdf):
67
  return gdf.select_dtypes(include=[float, int]).columns.tolist()
68
 
69
- def select_non_null(gdf, col_name):
70
- return gdf[~gdf[col_name].isna()]
71
-
72
- def select_null(gdf, col_name):
73
- return gdf[gdf[col_name].isna()]
74
-
75
  def app():
76
  st.title("Japan Vegetation Cover Fraction")
77
  st.markdown(
78
- """**Introduction:** This interactive dashboard is designed for visualizing Japan Fractional Vegetation Cover at town block levels.
79
- The data sources include [Vegetation Cover Fraction](https://zenodo.org/records/5553516) from a research project (https://doi.org/10.3130/aijt.28.521),
80
- and [Cartographic Boundary Files](https://www.e-stat.go.jp/gis/statmap-search?page=1&type=2&aggregateUnitForBoundary=A&toukeiCode=00200521&toukeiYear=2015&serveyId=A002005212015&coordsys=1&format=shape&datum=2000) from Census of Japan 2015.
81
- """
82
  )
83
 
84
  prefecture = st.selectbox("Prefecture", ["Tokyo", "Kanagawa", "Chiba", "Saitama"])
@@ -89,46 +51,41 @@ def app():
89
  st.error("Failed to load data. Please try again later.")
90
  return
91
 
92
- attributes = get_data_columns(gdf)
93
- selected_attribute = st.selectbox("Select attribute to visualize", attributes)
 
 
 
 
94
 
95
- row2_col1, row2_col2, row2_col3, row2_col4, row2_col5, row2_col6 = st.columns(
96
- [0.6, 0.68, 0.7, 0.7, 1.5, 0.8]
97
- )
98
 
99
- with row2_col1:
 
100
  palette = st.selectbox("Color palette", color_palettes, index=color_palettes.index('Blues'))
101
- with row2_col2:
102
  n_colors = st.slider("Number of colors", min_value=2, max_value=20, value=8)
103
- with row2_col3:
104
- show_nodata = st.checkbox("Show nodata areas", value=True)
105
- with row2_col4:
106
  show_3d = st.checkbox("Show 3D view", value=False)
107
- with row2_col5:
108
  if show_3d:
109
- elev_scale = st.slider(
110
- "Elevation scale", min_value=1, max_value=1000000, value=1, step=10
111
- )
112
- with row2_col6:
113
- st.info("Press Ctrl and move the left mouse button.")
114
- else:
115
- elev_scale = 1
116
-
117
- # Create a list of colors based on the selected palette and number of colors
118
  cmap = plt.get_cmap(palette)
119
  colors = [cmap(i / (n_colors - 1)) for i in range(n_colors)]
120
  hex_colors = ['#%02x%02x%02x' % (int(r * 255), int(g * 255), int(b * 255)) for r, g, b, _ in colors]
121
 
122
- color_scale = cm.LinearColormap(colors=hex_colors, vmin=gdf[selected_attribute].min(), vmax=gdf[selected_attribute].max())
123
- gdf['color'] = gdf[selected_attribute].apply(lambda x: color_scale(x))
124
- gdf['color'] = gdf['color'].apply(lambda x: [int(x[1:3], 16), int(x[3:5], 16), int(x[5:7], 16)])
125
-
126
- gdf_null = select_null(gdf, selected_attribute)
127
- gdf = select_non_null(gdf, selected_attribute)
128
 
129
  layer = pdk.Layer(
130
  "GeoJsonLayer",
131
- gdf.__geo_interface__,
132
  pickable=True,
133
  opacity=0.8,
134
  stroked=True,
@@ -136,43 +93,25 @@ def app():
136
  extruded=show_3d,
137
  wireframe=True,
138
  get_elevation=f"properties.{selected_attribute}" if show_3d else None,
139
- elevation_scale=elev_scale,
140
  get_fill_color="properties.color",
141
  get_line_color=[0, 0, 0],
142
  get_line_width=2,
143
  line_width_min_pixels=1,
144
  )
145
 
146
- if show_nodata:
147
- nodata_layer = pdk.Layer(
148
- "GeoJsonLayer",
149
- gdf_null.__geo_interface__,
150
- pickable=True,
151
- opacity=0.2,
152
- stroked=True,
153
- filled=True,
154
- extruded=False,
155
- get_fill_color=[200, 200, 200],
156
- get_line_color=[0, 0, 0],
157
- get_line_width=2,
158
- line_width_min_pixels=1,
159
- )
160
- layers = [layer, nodata_layer]
161
- else:
162
- layers = [layer]
163
-
164
  view_state = pdk.ViewState(
165
- latitude=gdf.geometry.centroid.y.mean(),
166
- longitude=gdf.geometry.centroid.x.mean(),
167
  zoom=9,
168
  pitch=45 if show_3d else 0,
169
  )
170
 
171
  r = pdk.Deck(
172
- layers=layers,
173
  initial_view_state=view_state,
174
  map_style="mapbox://styles/mapbox/light-v9",
175
- tooltip={"text": "{NAME}\n{" + selected_attribute + "}"}
176
  )
177
 
178
  st.pydeck_chart(r)
@@ -180,6 +119,6 @@ def app():
180
  st.write(color_scale)
181
 
182
  if st.checkbox("Show raw data"):
183
- st.write(gdf[[selected_attribute, 'NAME']])
184
 
185
  app()
 
12
 
13
  st.set_page_config(layout="wide")
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  # Data source
16
  data_links = {
17
  "Tokyo": "https://raw.githubusercontent.com/kunifujiwara/data/master/frac_veg/FRAC_VEG_Tokyo.geojson",
 
28
  response = requests.get(data_links[prefecture])
29
  if response.status_code == 200:
30
  geojson_data = json.loads(response.content)
31
+ gdf = gpd.GeoDataFrame.from_features(geojson_data['features'])
 
 
 
 
 
 
 
 
 
 
32
  return gdf
33
  else:
34
  st.error(f"Failed to fetch data for {prefecture}. Status code: {response.status_code}")
 
37
  def get_data_columns(gdf):
38
  return gdf.select_dtypes(include=[float, int]).columns.tolist()
39
 
 
 
 
 
 
 
40
  def app():
41
  st.title("Japan Vegetation Cover Fraction")
42
  st.markdown(
43
+ """**Introduction:** This interactive dashboard visualizes Japan Fractional Vegetation Cover at town block levels."""
 
 
 
44
  )
45
 
46
  prefecture = st.selectbox("Prefecture", ["Tokyo", "Kanagawa", "Chiba", "Saitama"])
 
51
  st.error("Failed to load data. Please try again later.")
52
  return
53
 
54
+ # City filter
55
+ cities = sorted(gdf['CITY_NAME_x'].unique().tolist())
56
+ selected_cities = st.multiselect("Select cities to display", cities, default=cities)
57
+
58
+ # Filter GeoDataFrame based on selected cities
59
+ gdf_filtered = gdf[gdf['CITY_NAME_x'].isin(selected_cities)]
60
 
61
+ attributes = get_data_columns(gdf_filtered)
62
+ selected_attribute = st.selectbox("Select attribute to visualize", attributes)
 
63
 
64
+ col1, col2, col3, col4 = st.columns(4)
65
+ with col1:
66
  palette = st.selectbox("Color palette", color_palettes, index=color_palettes.index('Blues'))
67
+ with col2:
68
  n_colors = st.slider("Number of colors", min_value=2, max_value=20, value=8)
69
+ with col3:
 
 
70
  show_3d = st.checkbox("Show 3D view", value=False)
71
+ with col4:
72
  if show_3d:
73
+ elev_scale = st.slider("Elevation scale", min_value=1, max_value=1000000, value=1, step=10)
74
+
75
+ # Create color scale
 
 
 
 
 
 
76
  cmap = plt.get_cmap(palette)
77
  colors = [cmap(i / (n_colors - 1)) for i in range(n_colors)]
78
  hex_colors = ['#%02x%02x%02x' % (int(r * 255), int(g * 255), int(b * 255)) for r, g, b, _ in colors]
79
 
80
+ vmin, vmax = gdf_filtered[selected_attribute].min(), gdf_filtered[selected_attribute].max()
81
+ color_scale = cm.LinearColormap(colors=hex_colors, vmin=vmin, vmax=vmax)
82
+
83
+ gdf_filtered['color'] = gdf_filtered[selected_attribute].apply(lambda x: color_scale(x))
84
+ gdf_filtered['color'] = gdf_filtered['color'].apply(lambda x: [int(x[1:3], 16), int(x[3:5], 16), int(x[5:7], 16)])
 
85
 
86
  layer = pdk.Layer(
87
  "GeoJsonLayer",
88
+ gdf_filtered.__geo_interface__,
89
  pickable=True,
90
  opacity=0.8,
91
  stroked=True,
 
93
  extruded=show_3d,
94
  wireframe=True,
95
  get_elevation=f"properties.{selected_attribute}" if show_3d else None,
96
+ elevation_scale=elev_scale if show_3d else 1,
97
  get_fill_color="properties.color",
98
  get_line_color=[0, 0, 0],
99
  get_line_width=2,
100
  line_width_min_pixels=1,
101
  )
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  view_state = pdk.ViewState(
104
+ latitude=gdf_filtered.geometry.centroid.y.mean(),
105
+ longitude=gdf_filtered.geometry.centroid.x.mean(),
106
  zoom=9,
107
  pitch=45 if show_3d else 0,
108
  )
109
 
110
  r = pdk.Deck(
111
+ layers=[layer],
112
  initial_view_state=view_state,
113
  map_style="mapbox://styles/mapbox/light-v9",
114
+ tooltip={"text": "{CITY_NAME_x}\n{" + selected_attribute + "}"}
115
  )
116
 
117
  st.pydeck_chart(r)
 
119
  st.write(color_scale)
120
 
121
  if st.checkbox("Show raw data"):
122
+ st.write(gdf_filtered[['CITY_NAME_x', selected_attribute]])
123
 
124
  app()