def plot_temperatures_map(geojson_map_file_name: str, type_of_map: str, dataframe: dict, year: int) -> None: """Plot a map that shows the daily mean temperatures in different provinces and territories in Canada. geojson_map_file_name a file containing the borders of each of the provinces. The type_of_map indicates whether the program is plotting the raw data or if it is plotting the differences. The dataframe is the dictionary that is read to plot the map. The function will take data from the year specified. """ province_borders = json.load(open(geojson_map_file_name, 'r')) # convert data into a logarithmic scale log_values = [] for temp in dataframe[year]: if temp <= 0: list.append(log_values, math.log10(0.00000000001)) else: list.append(log_values, math.log10(temp)) tickvals = list(range(math.floor(min(log_values)), math.ceil(max(log_values)))) fig = px.scatter_geo(dataframe, lat='latitudes', lon='longitudes', geojson=province_borders, # locations='id', locationmode='country names', color=log_values, hover_data=[year], scope='north america', size_max=100, center=dict(lon=-96.4835, lat=62.2400), title='Daily Mean Temperatures ' + type_of_map + ' (Units: Celsius)') fig.update_geos(fitbounds='geojson', visible=True) fig.update_layout(coloraxis_colorbar=dict(title="SCALE", tickvals=tickvals, ticktext=[math.pow(10, tickval) for tickval in tickvals])) fig.show()
def plot_map(self): geolocator = Nominatim(user_agent="TwAna") cat_color = {'negative': 'red', 'positive': 'green', 'neutral': 'blue'} loca_info = { 'latitude': [], 'longitude': [], 'color': [], 'size': [], 'senti_label': [] } for user_loc, cat, like_count in zip(self.data_dict['location'], self.data_dict['senti_label'], self.data_dict['favorite_count']): try: location = geolocator.geocode(user_loc) if location: loca_info['latitude'].append(location.latitude) loca_info['longitude'].append(location.longitude) loca_info['color'].append(cat_color[cat]) loca_info['size'].append(120 + like_count * 0.1) loca_info['senti_label'].append(cat) except: pass gapminder = px.data.gapminder().query("year==2007") fig = px.scatter_geo( gapminder, lat=loca_info['latitude'], lon=loca_info['longitude'], color=loca_info['senti_label'], hover_name=loca_info['senti_label'], size=loca_info['size'], ) fig.show()
def globe(df): argdf=df argdf.rename(columns={'Continent':'O'},inplace=True) fig = px.scatter_geo(df, lat='Latitude',lon='Longtitude', color='O', hover_name="Country", # column added to hover information size="Confirmed", text="City", height=800,width=1800 ) fig.update_geos(projection_type="orthographic", showcountries=True, countrycolor="Red", showland=True, landcolor="lime", showocean=True, oceancolor="midnightblue",lakecolor="Blue" ) fig.update_layout( title_text='Global Spread of Corono', titlefont=dict( size=40, color='Red' ) ) return fig
import pandas as pd import plotly.express as px # Read the cvs file df1 = pd.read_csv( "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv", sep=",") # Take a look to df1 print(df1.head()) # Using Plotly library to generate maps fig = px.scatter_geo(df1, lat="Lat", lon="Long", size=((df1["4/5/20"])), hover_name="Country/Region", color=(df1["4/5/20"]) / 1000, projection="natural earth") fig.show()
fig = px.density_mapbox( carshare, lat="centroid_lat", lon="centroid_lon", z="peak_hour", ) fig.write_html(os.path.join(dir_name, "density_mapbox.html"), auto_play=False) import plotly.express as px gapminder = px.data.gapminder() fig = px.scatter_geo( gapminder, locations="iso_alpha", color="continent", hover_name="country", size="pop", animation_frame="year", projection="natural earth", ) fig.write_html(os.path.join(dir_name, "scatter_geo.html"), auto_play=False) import plotly.express as px gapminder = px.data.gapminder() fig = px.line_geo( gapminder.query("year==2007"), locations="iso_alpha", color="continent", projection="orthographic", )
import dash_html_components as html from dash.dependencies import Input, Output, State from dataframe_populator_rough import dataframe_populator, trend_name_populator import plotly.graph_objects as go import plotly.express as px import pandas as pd import numpy as np import json external_stylesheets = ['styles.css', 'custom_styles.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) #Read the data for globe globe_data = pd.read_csv('final_woeid.csv') globe_fig = px.scatter_geo(globe_data, locations='Alpha-3_code', hover_name='Location', projection="natural earth") app.layout = html.Div([ #Div containing Logo and title text html.Div([ html.Img(src='assets/twitter_logo.png', id='twitLogo'), html.H1(children='Twit-Viz', id='pageTitle') ], style={ 'width': '100%', 'position': 'relative' }), dcc.Tabs( [
#!/usr/bin/env python3 import pandas as pd import plotly as ply import plotly.express as px import time url = 'http://api.open-notify.org/iss-now.json' while True: df = pd.read_json(url) df['latitude'] = df.loc['latitude', 'iss_position'] df['longitude'] = df.loc['longitude', 'iss_position'] df.reset_index(inplace=True) #print(df) df = df.drop(['index', 'message'], axis=1) print(df) fig = px.scatter_geo(df, lat='latitude', lon='longitude') ply.offline.plot(fig, filename="ISS.html", auto_open=False) time.sleep(45)
df = pd.read_json(url) # In[4]: df # In[5]: df["latitude"] = df.loc["latitude", "iss_position"] df["longitude"] = df.loc["longitude", "iss_position"] df.reset_index(inplace=True) # In[6]: df # In[7]: df = df.drop(["index", "message"], axis=1) # In[8]: df # In[11]: fig = px.scatter_geo(df, lat="latitude", lon="longitude") fig.show()
# Das gleiche machen wir für die Spalte `lat`. # In[8]: df['lat'] = df['coord'].apply(lambda x: x.strip('Point()').split()[1]) df['lat'] = df['lat'].astype(float) df['lat'] # Nun binden wir `plotly.express` ein und erstellen eine Karte. # In[9]: import plotly.express as px # In[10]: px.scatter_geo(df, lon='lon', lat='lat', scope='europe', text='place') # In[ ]:
def create_index(): url = 'http://api.open-notify.org/iss-now.json' df = pd.read_json(url) con = sqlite3.connect('location.db') df = df.append( { 'timestamp': '2021-04-16 14:25:57', 'iss_position': 1, 'message': 'success' }, ignore_index=True) df = df.append( { 'timestamp': '2021-04-16 14:25:57', 'iss_position': 1, 'message': 'success' }, ignore_index=True) df = df.append( { 'timestamp': '2021-04-16 14:25:57', 'iss_position': 1, 'message': 'success' }, ignore_index=True) df = df.append( { 'timestamp': '2021-04-16 14:25:57', 'iss_position': 1, 'message': 'success' }, ignore_index=True) df = df.append( { 'timestamp': '2021-04-16 14:25:57', 'iss_position': 1, 'message': 'success' }, ignore_index=True) df = df.append( { 'timestamp': '2021-04-16 14:25:57', 'iss_position': 1, 'message': 'success' }, ignore_index=True) df = df.append( { 'timestamp': '2021-04-16 14:25:57', 'iss_position': 1, 'message': 'success' }, ignore_index=True) df = df.append( { 'timestamp': '2021-04-16 14:25:57', 'iss_position': 1, 'message': 'success' }, ignore_index=True) df = df.append( { 'timestamp': '2021-04-16 14:25:57', 'iss_position': 1, 'message': 'success' }, ignore_index=True) df = df.append( { 'timestamp': '2021-04-16 14:25:57', 'iss_position': 1, 'message': 'success' }, ignore_index=True) df = df.append( { 'timestamp': '2021-04-16 14:25:57', 'iss_position': 1, 'message': 'success' }, ignore_index=True) df = df.append( { 'timestamp': '2021-04-16 14:25:57', 'iss_position': 1, 'message': 'success' }, ignore_index=True) df = df.append( { 'timestamp': '2021-04-16 14:25:57', 'iss_position': 1, 'message': 'success' }, ignore_index=True) cursorObj = con.cursor() latitudes = [ lat[0] for lat in cursorObj.execute("SELECT latitude from coordenadas") ] df['latitud'] = latitudes longitudes = [ lat[0] for lat in cursorObj.execute("SELECT longitude from coordenadas") ] df['longitud'] = longitudes fig = px.scatter_geo(df, lat='latitud', lon='longitud') fig.write_html('index.html', auto_open=False) shutil.move("index.html", "templates/index.html")
def update_click_map(selectedData, date, hoverData, inputData): """ click to select a airport to find the detail information :param selectedData: :param date: :param hoverData: :return: """ timestamp = pd.to_datetime(date) if date else 0 fig = px.scatter_geo(airports_info, scope="usa", lat=airports_info["LATITUDE"], lon=airports_info["LONGITUDE"], hover_name=airports_info["IATA_CODE"], color="COLOR_MAP", color_discrete_map="identity") fig.update_layout(hovermode="closest", margin=dict(l=5, r=0, t=20, b=20), clickmode="event+select", template='ggplot2') if inputData: origin_lon = location_dic[inputData]['lon'] origin_lat = location_dic[inputData]['lat'] airport = inputData infos = airports[(airports["ORIGIN_AIRPORT"] == airport) & (airports["DATE"] == timestamp)] if timestamp != 0 \ else overview_destination[overview_destination["ORIGIN_AIRPORT"] == airport] destinations = infos["DESTINATION_AIRPORT"].tolist( )[0] if infos["DESTINATION_AIRPORT"].tolist() else [] points = airports_info[airports_info["IATA_CODE"].isin(destinations) | (airports_info["IATA_CODE"] == airport)] points["COLOR_MAP"] = "#525252" fig = px.scatter_geo(airports_info, scope="usa", lat=points["LATITUDE"], lon=points["LONGITUDE"], hover_name=points["IATA_CODE"], hover_data=None, color=points["COLOR_MAP"], color_discrete_map="identity") fig.update_layout(clickmode="event+select", margin=dict(l=0, r=0, t=20, b=20), template="ggplot2") for des in destinations: fig.add_trace( go.Scattergeo(lon=[origin_lon, location_dic[des]["lon"]], lat=[origin_lat, location_dic[des]["lat"]], mode="lines", line=dict(width=1, color='#cb181d'), marker=dict(color='#cb181d'), hoverinfo="skip", showlegend=False)) return fig if selectedData and inputData: point_dict = selectedData["points"][0] origin_lon = point_dict['lon'] origin_lat = point_dict['lat'] airport = point_dict['hovertext'] infos = airports[(airports["ORIGIN_AIRPORT"] == airport) & (airports["DATE"] == timestamp)] if timestamp != 0 \ else overview_destination[overview_destination["ORIGIN_AIRPORT"] == airport] destinations = infos["DESTINATION_AIRPORT"].tolist( )[0] if infos["DESTINATION_AIRPORT"].tolist() else [] points = airports_info[airports_info["IATA_CODE"].isin(destinations) | (airports_info["IATA_CODE"] == airport)] points["COLOR_MAP"] = "#525252" fig = px.scatter_geo(airports_info, scope="usa", lat=points["LATITUDE"], lon=points["LONGITUDE"], hover_name=points["IATA_CODE"], hover_data=None, color=points["COLOR_MAP"], color_discrete_map="identity") fig.update_layout(clickmode="event+select") fig.update_layout(margin=dict(l=0, r=0, t=20, b=20), template="ggplot2") for des in destinations: fig.add_trace( go.Scattergeo(lon=[origin_lon, location_dic[des]["lon"]], lat=[origin_lat, location_dic[des]["lat"]], mode="lines", line=dict(width=1, color='#cb181d'), marker=dict(color='#cb181d'), hoverinfo="skip", showlegend=False)) return fig # hover的时候显示hover的点可以去到的机场 elif hoverData: point_dict = hoverData["points"][0] origin_lon = point_dict['lon'] origin_lat = point_dict['lat'] airport = point_dict['hovertext'] infos = airports[(airports["ORIGIN_AIRPORT"] == airport) & (airports["DATE"] == timestamp)] if timestamp != 0 \ else overview_destination[overview_destination["ORIGIN_AIRPORT"] == airport] # infos = airports[(airports["ORIGIN_AIRPORT"]==airport) & (airports["DATE"]==timestamp)] destinations = infos["DESTINATION_AIRPORT"].tolist( )[0] if infos["DESTINATION_AIRPORT"].tolist() else [] for des in destinations: fig.add_trace( go.Scattergeo(lon=[origin_lon, location_dic[des]["lon"]], lat=[origin_lat, location_dic[des]["lat"]], mode="lines", line=dict(width=1, color='#cb181d'), hoverinfo="skip", showlegend=False)) # fig.update_layout(clear_on_unhover=True) return fig else: return fig
def update_graph(country_code, strictness, clicks): country = country_alpha2_to_country_name(country_code) dest_lat = latlon.loc[latlon['name'] == country]['latitude'].iloc[0] dest_lon = latlon.loc[latlon['name'] == country]['longitude'].iloc[0] dest_flights = flights_data[flights_data['dest_airport_country'] == country] if dest_flights.size == 0: fig = px.scatter_geo(lat=[dest_lat], lon=[dest_lon], projection='natural earth') markdown = dcc.Markdown( "#### NO DATA AVAILABLE FOR THE SELECTED COUNTRY") fig.update_layout(margin=dict(l=0, r=0, t=0, b=0)) else: if clicks % 2 == 0: fig = px.choropleth(dest_flights, locationmode="ISO-3", locations='CC', color='flight_capacity', color_continuous_scale="spectral", template='seaborn', projection='natural earth') label = "View Positive Rate" else: fig = px.choropleth(inf_choropleth_recent_data, locationmode="ISO-3", locations='iso_code', color='positive_rate', color_continuous_scale="reds", template='seaborn', projection='natural earth') label = "View Flight Capacity" fig.update_layout(margin=dict(l=0, r=0, t=0, b=0)) country_3 = a2toa3[country_code] country_cr = risk_factors[risk_factors['iso_code'] == country_3] for val in dest_flights.itertuples(): source = val[1] if strictness == 'high' and not country_name_to_country_alpha3( source) in country_cr['sources_y'].iloc[0]: continue try: lat = latlon.loc[latlon['name'] == source]['latitude'].iloc[0] lon = latlon.loc[latlon['name'] == source]['longitude'].iloc[0] fig = fig.add_scattergeo(lat=[lat, dest_lat], lon=[lon, dest_lon], line=dict(width=1, color='#1F1F1F'), mode='lines+text', text="✈️", showlegend=False) except: continue strictness_level = { 'low': "Lowest", 'med': "Moderate", 'high': "Highest" }[strictness] markdown = dcc.Markdown(text.format(country, strictness_level)) return fig, markdown, label
with open(input_folder + "/resulting_table.csv", "w") as result_f: wr = csv.writer(result_f, quoting=csv.QUOTE_ALL) wr.writerows(data) # Lets transform data to a dataframe and present it using plotly df = pd.DataFrame(data, columns=columns) df = df.sort_values(by=["Date", "Location"]) hover_columns = ["Location", "Date", "New Cases per Million", "School Status"] info_box_values = df[hover_columns] fig = px.scatter_geo( df, locations=columns[0], # map position (iso code) size=columns[-2], # circle size color=columns[-1], # circle color # color_discrete_sequence=color_status_texts, hover_name=columns[2], # Location hover_data=info_box_values, # location, date, new cases per million, circle color # TODO change column name animation_frame=columns[3], # Date # animation_group=columns[-1], size_max=10, # circle max size projection="natural earth") fig.update_layout( title={ 'text': "Measures on educational institutes in combination with sum of new cases per million in the last 7 days", 'y': 1, 'x': 0.5, 'xanchor': 'center', 'yanchor': 'top' })
plt.savefig("static/images/plot8.png") #---plot8--- df3=df[357:430] df4=df[431:] before = df3.sum(axis=0) after = df4.sum(axis=0) df5 = before.compare(after) df5.plot.bar(figsize=(20, 10)) plt.legend('', '') plt.savefig("static/images/plot9.png") #---plot9--- plt.figure(figsize=(20,20)) fig = px.scatter_geo(df_long,'latitude','longitude', color="Regions", hover_name="States", size="Usage", scope='asia') fig.update_geos(lataxis_range=[5,35], lonaxis_range=[65, 100]) app = Flask(__name__) @app.route('/') def home(): return render_template('index.html',headings1=df.columns[:13],headings2=df_long.columns,data1=a1,data2=a2) if __name__ == "__main__": app.run(debug=True)
# uncomment to save the file # gdf.to_file("data/semiology_of_graphics_points.geojson", driver="GeoJSON") # In[8]: # plot the resulting `services` data import plotly.express as px fig = px.scatter_geo(gdf, lat=gdf.geometry.y, lon=gdf.geometry.x, size="services", size_max=30, fitbounds="geojson", projection="mercator", basemap_visible=False) basepolygons = ( px.choropleth(df, geojson=df.geometry, locations=df.index, color_discrete_sequence=["white"]) .update_traces(marker_line_color="lightgrey", showlegend=False) .data[0] ) fig.update_layout(showlegend=False, height=400, margin=dict(t=40, b=0, r=0, l=0)) fig.add_trace(basepolygons) fig.show("svg") # In[ ]:
print(newCases2) data = { 'id': id, 'activeCases': activeCases, 'iso_alpha': iso_alpha, 'country': country, 'firstCase': firstCase, 'newCases': newCases2, 'seriousCritical': seriousCritical, 'totalCase': totalCases, 'totalDeath': totalDeath, 'totalRecovered': totalRecovered } # Create DataFrame df = pd.DataFrame(data) with pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also print(df) fig = px.scatter_geo(df, locations="iso_alpha", color="newCases", size="newCases", hover_name="country", projection="natural earth") fig.show()
import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd import plotly.express as px import plotly.graph_objects as go d = pd.read_csv("data.csv") external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.layout = html.Div(children=[ html.H1(children='Health'), html.Div(children="Unsafe drinking water in countries"), dcc.Graph( id='country-geo-graph', figure= px.scatter_geo(d, locations="iso", color="UWD", hover_name="country", size="UWD",template="plotly_white", projection="natural earth") ), html.P(children=''' Visualising current health conditions globally ''') ]) if __name__ == '__main__': app.run_server(debug=True)
def main(): url = f"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv" df = pd.read_csv(url, error_bad_lines=False) xml=pd.read_excel(r'C:\Users\raffr\Downloads\COVID-19-geographic-disbtribution-worldwide-2020-03-24.xlsx') #po wrzucaniu na gita czyta inaczej.plik w repo pobrac i zmienic sciezke frame=pd.DataFrame(xml) allcountry=pd.read_csv(r'https://raw.githubusercontent.com/rafal-lab/Corona_project/master/word.csv') Poland = find_country(frame , 'Poland') rysunek = Poland.plot(y=['Cases', 'Deaths'], x='DateRep', figsize=(12, 8), marker='*', title='Liczba przypadków COVID-19 w Polsce danego dnia', grid=True) formated_gdf=sort_by_country(frame) fig = px.scatter_geo(formated_gdf, locations="Countries and territories", locationmode='country names', color="Deaths", size='size', hover_name="Countries and territories", range_color= [0, 80], projection="natural earth", title="Liczba smierci 24.03.2020 COVID-19 na swiecie" ) fig.show() fig2 = px.choropleth(formated_gdf, locations="Countries and territories", locationmode='country names', color="Deaths", hover_name="Countries and territories", range_color= [0, 150], projection="natural earth", title='Smiertelnosc COVID19 na swiecie w dniu 24.03.2020') fig2.show() USA=allcountry.loc[allcountry['Country/Region']=='US'].sort_values(by='3/23/20') USA=USA.fillna(value=0) us=pd.DataFrame(USA[["Province/State", "Country/Region", 'Lat','Long','3/23/20']].sort_values(by='3/23/20')) us=us.rename(columns={'3/23/20':'Deaths'}) #wybieramy dane z USA z określonych stanów fig3=px.scatter_geo(us,locations='Province/State',locationmode='USA-states',scope='usa',range_color=[0,20],color='Deaths',size='Deaths',title='Liczba zgonów w USA w dniu 23/03/2020') fig3.show() nb_of_cases_in_Italy=find_country(frame,'Italy') lista=list(nb_of_cases_in_Italy["Cases"]) #bierzemy tylko przypadki nb_cs=pd.DataFrame(nb_of_cases_in_Italy) lista.reverse() for i in range(len(lista)):# PĘTLA DO SUMOWANIA PRZYPADKOW if(i==0 ): pass else: lista[i] += lista[i-1] lista.reverse() lista = np.asarray(lista) #lista wszystkich przypadków nb_cs['sum_in_Italy']=lista #dodajemy liste do tabeli i rysujemy cases_Italy_print=nb_cs.plot(x='DateRep',y='sum_in_Italy',figsize=(12,8), marker='o', title="Liczba przypadkow we Włoszech",grid=True) #wybieranie poszczegolnych krajow i dodawanie do tabeli Hiszpania = pd.DataFrame(find_country(frame,'Spain')) cases_in_spain = np.array(Hiszpania['Cases']) death_in_spain = np.array(Hiszpania['Deaths']) nb_cs['cs_in_Spain'] = cases_in_spain nb_cs['dth_in_Spain'] = death_in_spain nb_cs = nb_cs.rename(columns={'Cases': "cs_in_Italy"}) nb_cs = nb_cs.rename(columns={'Deaths': "dth_in_Italy"}) USA = pd.DataFrame(find_country(frame, 'USA')) cases_in_USA = np.array(USA['Cases']) death_in_USA = np.array(USA['Deaths']) nb_cs['cs_in_USA'] = cases_in_USA nb_cs['dth_in_USA'] = death_in_USA #suma przypadkow z krajow i dodanie do tabeli sum_in_spain = give_SUM(frame,'Spain') sum_in_USA = give_SUM(frame,"USA") nb_cs['sum_in_USA'] = sum_in_USA nb_cs['sum_in_Spain'] = sum_in_spain sum_dth_Spain = give_Death(frame,"Spain") sum_dth_USA = give_Death(frame,"USA") sum_dth_Italy = give_Death(frame,"Italy") nb_cs['sum_dth_in_Spain'] = sum_dth_Spain nb_cs['sum_dth_in_Italy'] = sum_dth_Italy nb_cs['sum_dth_in_USA'] = sum_dth_USA #rysowanie poszczegolnych wykresow nb_cs.plot(y=['cs_in_Italy', 'cs_in_Spain', 'cs_in_USA'], x='DateRep', figsize=(12, 8), marker='o', title='Wykres ilości nowych przypadków w Hiszpani, Włoszech i USA,każdego dnia',grid=True) nb_cs.plot(y=['dth_in_Italy', 'dth_in_Spain', 'dth_in_USA'], x='DateRep', figsize=(12, 8), marker='o', title='Wykres ilości śmierci w Hiszpani, Włoszech i USA,każdego dnia',grid=True) nb_cs.plot(y=['sum_in_Spain', 'sum_in_USA', 'sum_in_Italy'], x='DateRep', figsize=(12, 8), marker='o', title='Wykres sumarycznej ilości przypadkow w Hiszpani, Włoszech i USA',grid=True) nb_cs.plot(y=['sum_dth_in_Spain', 'sum_dth_in_USA', 'sum_dth_in_Italy'], x='DateRep', figsize=(12, 8), marker='o', title='Wykres sumarycznej ilości śmierci w Hiszpani, Włoszech i USA',grid=True) plt.show() #kolowe tabele narysowane w colabie! tb=table_of_country(df,'Spain','US','Italy') print(tb)
app = dash.Dash(__name__, external_stylesheets=stylesheets) app.title = "Sexy Dashboard" server = app.server bubble_map = px.scatter_geo( countries_df, size="Confirmed", projection="equirectangular", hover_name="Country_Region", color="Confirmed", locations="Country_Region", locationmode="country names", size_max=40, title="Confirmed By Country", template="plotly_dark", color_continuous_scale=px.colors.sequential.Oryel, hover_data={ "Confirmed": ":,", "Deaths": ":,", "Recovered": ":,", "Country_Region": False, }, ) bubble_map.update_layout(margin=dict(l=0, r=0, t=50, b=0), coloraxis_colorbar=dict(xanchor="left", x=0)) bars_graph = px.bar( totals_df, x="condition",
# Sicherheitshalber... geo.options.default_timeout = 10 # Um den Server nicht zu überlasten geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1) # Nimm im DataFrame aus jeder Zeile den Geburtsort und übergib den Wert an den # Geolokalisator, der die Koordination etc. abruft. Die zurückgegebenen Werte # werden in einer neuen Spalte abgelegt. # Wie eine For-Schleife, hier aber für Pandas. # df['GeoData'] = df['place_of_birth'].apply(geolocator.geocode) for d in data: if d['place_of_birth']: d['GeoData'] = geocode(d['place_of_birth']) d['Latitude'] = d['GeoData'].latitude d['Longitude'] = d['GeoData'].longitude # Jetzt kommt es zu Pandas # Erstelle einen neuen DataFrame und verweise auf ihn. df = pd.DataFrame(data) # Erstelle ein figure-Objekt, greife auf den DataFrame zurück... fig = px.scatter_geo(df, lat='Latitude', lon='Longitude', scope='europe', hover_data=['name', 'place_of_birth'], color='name') # Speiche das figure-Objekt in die Datei... fig.write_html('orte.html')
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import plotly.express as px import numpy as np sns.set(style='darkgrid') df = pd.read_csv("population_by_country_2020.csv") print(df.head()) # Draw distribution plot (kdeplot) sns.kdeplot(df['Population (2020)'], shade=True) plt.show() # Draw histogram plot sns.histplot(df, x='Population (2020)', color='red', kde=True) plt.show() # Map fig = px.scatter_geo(df, locations='Country (or dependency)', locationmode='country names', hover_name='Country (or dependency)', size='Population (2020)', projection='natural earth') fig.show()
def create_map(): cities_dict = { 'city': [], 'lat': [], 'lon': [], 'country': [], 'name': [], 'role': [], 'size': [] } from fedn import get_data dbpath = get_data('geolite2/GeoLite2-City.mmdb') with geoip2.database.Reader(dbpath) as reader: for combiner in self.control.statestore.list_combiners(): try: response = reader.city(combiner['ip']) cities_dict['city'].append(response.city.name) r = 1.0 # Rougly 100km w = r * math.sqrt(numpy.random.random()) t = 2.0 * math.pi * numpy.random.random() x = w * math.cos(t) y = w * math.sin(t) lat = str(float(response.location.latitude) + x) lon = str(float(response.location.longitude) + y) cities_dict['lat'].append(lat) cities_dict['lon'].append(lon) cities_dict['country'].append( response.country.iso_code) cities_dict['name'].append(combiner['name']) cities_dict['role'].append('Combiner') cities_dict['size'].append(10) except geoip2.errors.AddressNotFoundError as err: print(err) with geoip2.database.Reader(dbpath) as reader: for client in self.control.statestore.list_clients(): try: response = reader.city(client['ip']) cities_dict['city'].append(response.city.name) cities_dict['lat'].append(response.location.latitude) cities_dict['lon'].append(response.location.longitude) cities_dict['country'].append( response.country.iso_code) cities_dict['name'].append(client['name']) cities_dict['role'].append('Client') # TODO: Optionally relate to data size cities_dict['size'].append(6) except geoip2.errors.AddressNotFoundError as err: print(err) config = self.control.statestore.get_config() cities_df = pd.DataFrame(cities_dict) if cities_df.empty: return False fig = px.scatter_geo(cities_df, lon="lon", lat="lat", projection="natural earth", color="role", size="size", hover_name="city", hover_data={ "city": False, "lon": False, "lat": False, 'size': False, 'name': True, 'role': True }) fig.update_geos(fitbounds="locations", showcountries=True) fig.update_layout( title="FEDn network: {}".format(config['network_id'])) fig = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) return fig
import numpy as np import seaborn as sns import plotly import plotly.offline as py import matplotlib.pyplot as plt import plotly.graph_objects as go import plotly.express as px import plotly.io as pio df = pd.read_csv( 'statistic_id456786_cancer-rate-in-selected-european-countries-in-2012.csv' ) print(df.head()) df = df.dropna() print(df.isnull().values.any()) df['per100,000 '].astype(int) print(df.columns) print(df.info()) fig = px.scatter_geo(df, locations="Country", color="per100,000 ", hover_name="Country", size="per100,000 ", projection="orthographic", locationmode='country names', scope='europe', title='Cancer Rate in Europe 2012') fig.show() py.plot(fig, filename='europecancerrates.html') pio.write_html(fig, file='index6.html', auto_open=True)
gdp=('gdp', 'first'), gdp_per_capita=('gdp_per_capita', 'first'), iso_alpha=('iso_alpha', 'first'), ) df_agg = df_agg.reset_index() df_agg = df_agg.sort_values(by=['year', 'country']) years = list(df_agg.year.unique()) op_year = st.sidebar.selectbox('Select the year.', (years), index=years.index(2015)) op_color = st.sidebar.selectbox( 'Select the color.', ('gdp_per_capita', 'region', 'sub_region', 'gdp')) op_size = st.sidebar.selectbox('Select the size.', ('suicide_100k_pop', 'suicide_sum')) st.write('World map for year ' + str(op_year)) fig = px.scatter_geo(df_agg[df_agg.year == op_year], locations="iso_alpha", color=op_color, hover_name="country", size=op_size, hover_data={ 'suicide_sum': True, "suicide_100k_pop": ":.2f", "population": True, "gdp_per_capita": True, "iso_alpha": False }, projection="orthographic") fig.update_layout(width=800, height=800, hoverlabel_align='right') st.plotly_chart(fig, use_container_width=True)
import plotly.express as px fig = px.scatter_geo(lat=[51.555051, 55.753215], lon=[46.013428, 37.622504], size=[800000, 12000000])
seen[loc_str] = {'lat': geocode.latlng[0], 'lng': geocode.latlng[1]} lat.append(seen[loc_str]['lat']) lng.append(seen[loc_str]['lng']) location_names.append(loc_str) try: json.dump(seen, open('loaction_dump.json', 'w')) except PermissionError: pass locations['lat'] = lat locations['lng'] = lng locations['Location'] = location_names locations['# of Classes'] = locations.groupby(['lat', 'lng'])['lat'].transform('count') fig = px.scatter_geo(locations, lat="lat", lon='lng', size='# of Classes', projection='albers usa', hover_data={'lat': False, 'lng': False, '# of Classes': True, 'Location': True}, title='Class Locations', size_max=25) # fig.show() '## Analysis' with st.beta_expander('General Statistics'): st.success(f'There have been **{len(locations)}** classes taught with these filter options.') st.success(f'The classes were taught in **{len(set(location_names))}** different cities.') st.plotly_chart(fig, use_container_width=True) st.success(f'These classes reached **{len(df)}** students.') heritage_counts = df["History & Heritage Positive Motivators?"].str.lower().value_counts() yes = heritage_counts.get('yes', 1) no = heritage_counts.get('no', 0) st.success(f'**{100 * yes / (yes + no):.2f}%** of the ' f'{(yes + no)} students surveyed, said heritage/history ' f'are positive motivators for health.')
st.sidebar.markdown('Mapping of Covid 19 spread') map_selector = st.sidebar.selectbox('Choose a map', ['African Bubble Map', 'World Bubble Map'], key='1') df_maps = data.groupby(['date', 'country', 'iso_alpha', 'region']).sum().reset_index() df_maps = df_maps[df_maps.date >= '2020-02-25'] if not st.sidebar.checkbox('Hide', True): st.subheader('Mapping of COvid 19 spread') if map_selector == 'African Bubble Map': fig = px.scatter_geo( df_maps, locations='iso_alpha', animation_frame='date', color='region', size='confirmed', size_max=60, scope='africa', hover_data=['confirmed', 'deaths', 'recovered', 'active'], hover_name='country') fig.layout.updatemenus[0].buttons[0].args[1]['frame']['duration'] = 2 fig.update_layout(title='Evolution cases of Covid-19 in Africa', height=500) st.plotly_chart(fig) comment = st.markdown( "This map shows the evolution infections on the continent. We note that South Africa is the country with the most infections." ) else: fig = px.scatter_geo(data2, locations='iso_code', animation_frame='date',
"https://s3.amazonaws.com/rawstore.datahub.io/9dc095afacc22888e66192aa23e71314.csv" ) fig2 = px.sunburst(df, path=['Continents', 'Country'], values='Confirmed', color='Deaths', hover_data=['Country'], color_continuous_scale='RdBu', color_continuous_midpoint=np.average( df['Deaths'], weights=df['Confirmed'])) fig3 = px.scatter_geo(df, locationmode='country names', locations='Country', color='Continents', hover_name='Country', size='Confirmed', projection='natural earth') fig4 = px.area(df1, x="Date", y="Recovered", color="Country", line_group="Country") fig4.update_xaxes(rangeslider_visible=True) #fig4 = px.area(df1, facet_col=['Confirmed','Recovered','Deaths'], facet_col_wrap=3) # ------------------------------------------------------------------------------ # App layout app.layout = html.Div([ html.Div([
pio.renderers.default = "browser" # Load the final database and the ozone train/dev/test splits db = pd.read_csv( '01_Data/01_Carbon_emissions/AirNow/World_all_locations_2020_avg_clean.csv', dtype={ 'Unique_ID': str, 'Location_type': str, 'Zipcode': str, 'County': str, 'type': str, 'measurement': str, 'value': float, 'lat': float, 'lon': float, 'AQI_level': str }) splits = pd.read_csv('01_Data/03_Processed_data/OZONE/ozone_splits.csv') # Filter for ozone readings and get split ozone = db[db['type'] == 'OZONE'] ozone = ozone.merge(splits, how='left', validate='one_to_one', on='Unique_ID') # Plot fig = px.scatter_geo(ozone, lat=ozone['lat'], lon=ozone['lon'], color=ozone['dataset'], hover_name=ozone["Location_type"]) fig.show()
# Draw a title and some text to the app: st.title("People in Space & ISS Current Location") st.write("This app provides an overview about people who are in _space_ righ now") #people in space space = requests.get("http://api.open-notify.org/astros.json/") data = json.loads(space.text) nr = data["number"] st.write("Number of people in space right now is" + " " + str(nr) + ".") st.write("The names of those people are:") for item in data["people"]: st.write((item["name"])) # -------------------------PLOT SIMPLE MAP---------------------------- # Location url = 'http://api.open-notify.org/iss-now.json' df = pd.read_json(url) # Create new column called latitude and longitude and drop index and message df['latitude'] = df.loc['latitude', 'iss_position'] df['longitude'] = df.loc['longitude', 'iss_position'] df.reset_index(inplace=True) df = df.drop(['index', 'message'], axis=1) # Plot fig = px.scatter_geo(data_frame=df, lat='latitude', lon='longitude') fig.show()