def update_graph(n_clicks, select_id): global all_size, out_size # 이 경우 result_all에서 가져온 data를 사용하면 아웃라이어를 제거한 경우로 진행할 수 있고 # 쿼리를 날려서 가져오는 경우 원본 그대로 진행할 수 있다. feature = data[data.EPOPCON_ID == select_id].reset_index()[[ 'LATITUDE', 'LONGITUDE' ]] if len(feature) == 0: return { 'data': go.Scattergeo(), 'layout': { 'title': 'Out rate : {}%'.format(round(out_size / all_size * 100, 2)), 'geo': { 'scope': 'korea', 'lonaxis': { 'range': [124, 129] }, 'lataxis': { 'range': [35, 40] }, }, 'height': 1000 } } all_size = len(feature) model = KMeans(n_clusters=3) #클러스터 개수를 정한다. model.fit(feature) predict = pd.DataFrame(model.predict(feature)) predict.columns = ['predict'] r = pd.concat([feature, predict], axis=1) return { 'data': [ go.Scattergeo(lon=r[r.predict == cluster]['LONGITUDE'], lat=r[r.predict == cluster]['LATITUDE'], mode='markers', name=str(cluster) + '(' + str(len(r[r.predict == cluster])) + ')') for cluster in sorted(r['predict'].unique()) ], 'layout': { 'geo': { 'scope': 'korea', 'lonaxis': { 'range': [124, 129] }, 'lataxis': { 'range': [35, 40] }, }, 'height': 1000 } }
def update_value(interval): f = urllib.request.urlopen('http://www.celestrak.com/NORAD/elements/stations.txt') myfile = f.read() arr = myfile.decode().split("\r") #print ("result code: " + str(f.getcode())) tle_line1 = arr[1] tle_line2 = arr[2] #print (tle_line1,tle_line2) date = datetime.datetime.utcnow() tick = datetime.timedelta(0,300) date_n = date + datetime.timedelta(0,5400) df = pd.DataFrame() df2 = pd.DataFrame() for i in range(18): date = date + tick tle_rec = ephem.readtle(tle_name, tle_line1, tle_line2) tle = tle_rec.compute(date) lon_deg= math.degrees(tle_rec.sublong) lat_deg = math.degrees(tle_rec.sublat) #print(tle_rec.sublong, tle_rec.sublat, lon_deg, lat_deg) df = pd.DataFrame(data={'lon': [lon_deg], 'lat': [lat_deg], 'time': [date]}) df2 = df2.append(df) #print (df2) with urllib.request.urlopen(iss_url) as url: data = json.loads(url.read().decode()) lat = data['iss_position']['latitude'] lon = data['iss_position']['longitude'] d = {'lon': [lon], 'lat': [lat]} df = pd.DataFrame(data=d) data = [ go.Scattergeo( lon = df['lon'], lat = df['lat'], name = 'ISS', marker = dict(symbol='circle', size = 10, opacity = 0.7, color = "red"), hovertext = 'ISS Realtime Location'), go.Scattergeo( lon = df2.lon, lat = df2.lat, name = 'ISS Orbit (+5min - +90min)', mode = 'lines', opacity = 0.5, hovertext = df2.time, line = go.scattergeo.Line( width = 2.5, color = 'blue',))] fig=go.Figure(data=data, layout=layout) #fig.append_trace({'x':df2.lon,'y':df2.lat,'type':'scatter','name':'orbit'},1,1) return fig
def Ploter(): Lat_Long = [] for i in DB.DATABASE().GET_airport(): Lat_Long.append(i[1:4]) Data = pandas.DataFrame(numpy.array(Lat_Long), columns=['Code', 'Lat', 'Lng']) fig = go.Figure() fig.add_trace( go.Scattergeo(locationmode='USA-states', lon=Data['Lng'], lat=Data['Lat'], hoverinfo='text', text=Data['Code'], mode='markers', marker=dict(size=5, color='rgb(255, 0, 0)'))) fig.update_layout(title_text=' Visualisation des Airoports ', showlegend=True, geo=dict( scope='usa', showland=True, landcolor='rgb(0, 0, 0)', countrycolor='rgb(204, 204, 204)', )) fig.show() fig.write_image("plot.png")
def make_fig_1(value): table = master_elec metric = "Total Electricity net generation" if value == "lastValue": mult = 0.5 name = "Total generation" unit = "bln kWh" else: mult = 20 name = "Per capita generation" unit = "thousand kWh PP" df = table[table["label"] == metric] df["text"] = df["country"] + '<br>' + name + ": " + '<br>' + round( df[value], 2).astype('str') + " " + unit d = go.Figure( go.Scattergeo(lon=df["long"], lat=df["lat"], text=df['text'], hoverinfo='text', marker=dict(size=mult * df[value], line_width=0.5, sizemode='area', color="#636EFA"))) fig1 = go.Figure(data=d) fig1.update_layout(l_map) fig1.update_geos(projection_type="natural earth", lataxis_showgrid=False, lonaxis_showgrid=False, lataxis_range=[-60, 85]) return fig1
def plotPopCenter(df, title, path): colors = ["royalblue", "crimson", "lightseagreen", "orange", "lightgrey"] fig = go.Figure() # Make the Figure data = df_popcenter[df_popcenter.stname == 'New York'] fig.add_trace( go.Scattergeo(locationmode='USA-states', lon=df['longitude'], lat=df['latitude'], text=df['couname'], marker=dict(size=np.log(df['population']), line_color='rgb(40,40,40)', line_width=0.5, sizemode='area'))) # Update Layout fig.update_layout(title=title, geo=go.layout.Geo(scope='usa', lonaxis_range=[-150.0, -200.0], lataxis_range=[0.0, 0.0])) # Save static image pio.write_image(fig, path)
def makeScatterMap(value): #allData.rename(columns = {'Country/Region':'Country'}, inplace = True) if (value == 0): allData1 = allData[allData['dateStr'].isin(da1)] elif (value == 5): allData1 = allData[allData['dateStr'].isin(da2)] else: allData1 = allData[allData['dateStr'].isin(da3)] allData1['Country'] = allData1['Country/Region'] world_data = pd.merge(world_coordinates, allData1, on='Country') world_data['Confirmed'] = world_data['Confirmed'].astype(str) world_data['Deaths'] = world_data['Deaths'].astype(str) #world_data['Recovered']=world_data['Recovered'].astype(str) scl = [0,"rgb(150,0,0)"],[0.125,"rgb(100, 0, 0)"],[0.25,"rgb(0, 25, 0)"],\ [0.375,"rgb(0, 152, 0)"],[0.5,"rgb(44, 255, 0)"],[0.625,"rgb(151, 0, 0)"],\ [0.75,"rgb(255, 234, 0)"],[0.875,"rgb(255, 111, 0)"],[1,"rgb(255, 0, 0)"] data = [ go1.Scattergeo(lat=world_data['latitude'], lon=world_data['longitude'], text=world_data['Country'] + '\n' + 'Confirmed : ' + (world_data['Confirmed']) + '\n' + 'Deaths : ' + (world_data['Deaths']), marker=dict(color=(world_data['Recovered'] % 100) * 0.01, size=7, opacity=0.7)) ] fig = go1.Figure(data=data) fig.update_layout(title='World map', height=700) return fig
def update_figure(year_range): """ Triggered by user interaction with the rangeslider """ # filter dataset according to min/max of slider filtered_df = df[ (df.decimal_year < year_range[1]) & (df.decimal_year > year_range[0]) ] # update the color values marker.color = filtered_df['decl_api'] # replace the figure data with filtered data data = [ go.Scattergeo( lon = filtered_df["longitude"], lat = filtered_df["latitude"], text = filtered_df['label'], marker = marker ) ] # create new figure object to return to dash widget, no change in layout fig = go.Figure(data=data, layout=layout) return fig
def update_chart(trend): if trend == "Total energy consumption": metric="lastValue" mult=10 unit="QBtu" elif trend=="Energy consumption per capita": metric="MBtuPP" mult=1 unit="MBtu per person" else: metric="TBtuUSD" mult=10 unit="TBtu per USD GDP" table=master_cons[master_cons["country"]!="World"] df=table[table["label"]=="Total energy consumption"] df["text"]= df["country"] +'<br>' + trend + ": " + round(df[metric],2).astype('str') +" " +unit d = go.Figure(go.Scattergeo( lon=df["long"], lat=df["lat"], text = df['text'], hoverinfo = 'text', marker=dict( size= mult*df[metric], line_width=0.5, sizemode='area' ))) fig1=go.Figure(data=d) fig1.update_layout(l_map) fig1.update_geos(projection_type="natural earth", lataxis_showgrid=False, lonaxis_showgrid=False) return fig1
def createTweetWorldMap(df: pd.core.frame.DataFrame): ''' Given dataframe that contains columns corresponding to Longitude and Latitude, create a world map plot and mark the Tweet locations on the map. ''' df['Text'] = df['Date'] + ': \n' + df['Tweet'] fig = go.Figure( data=go.Scattergeo(lon=df['Longitude'], lat=df['Latitude'], text=df['Text'], mode='markers', marker=dict( symbol='circle', line=dict(width=1, color='rgba(102, 102, 102)'), colorscale='Viridis', cmin=0, ))) fig.update_layout( title= 'COVID-19 related Tweets across the world (January 2020 - March 2020) ', geo_scope='world', geo=dict( resolution=110, scope='world', showland=True, landcolor="rgb(250, 250, 250)", subunitcolor="rgb(217, 217, 217)", countrycolor="rgb(217, 217, 217)", countrywidth=0.6, subunitwidth=0.6, )) return fig
def build(self): Chart.build(self) keys = self._datasource.getKeyValues() values = self.getValues("values") lat = [] lon = [] opt = self._options.get("lat") if opt != None: lat = self._datasource.getValues(opt) opt = self._options.get("lon") if opt != None: lon = self._datasource.getValues(opt) self._data = [] geo = go.layout.Geo() geo.scope = "usa" #geo.projection = go.layout.geo.Projection(type='albers usa') #geo.showland = True #geo.landcolor = "rgb(217, 217, 217)" self._layout.geo = geo self._data.append(go.Scattergeo(text=keys,lat=lat,lon=lon,locationmode="USA-states"))
def update_graph4(input_data): data = go.Scattergeo( name="Product Cost", showlegend=True, mode="markers", lat=Graph4_Data.get("Latitude"), lon=Graph4_Data.get("Longitude"), text=Graph4_Data.get("Product Cost Values"), hovertext=Graph4_Data.get("Countries"), hovertemplate="Product Cost: $%{text: .0f}<br>Country: %{hovertext}", marker=dict(opacity=1, size=Graph4_Data.get("Product Cost Values"), sizeref=1000, sizemin=1, sizemode="area", gradient=dict(type="radial", color="red"), color="blue")) layout = { "geo": { "scope": "world", "showframe": True, "projection": { "type": "orthographic" }, #miller, orthographic, hide "showcountries": False, "showcoastlines": True }, "title": "Sum of Product Cost per Country (USD)", "hovermode": "closest", # "margin": {'l': 30, 'r': 10, 'b': 10, 't': 49} "clickmode": "event+select" } return {"data": [data], "layout": layout}
def makeScatterMapindia(value): #allData.rename(columns = {'Country/Region':'Country'}, inplace = True) #allData['Country'] = allData['Country/Region'] data1 = pd.merge(ind_df, India_coord, on='Name of State / UT') data1['Total cases'] = data1['Total cases'].astype(str) data1['Deaths'] = data1['Deaths'].astype(str) #world_data['Recovered']=world_data['Recovered'].astype(str) scl = [0,"rgb(150,0,0)"],[0.125,"rgb(100, 0, 0)"],[0.25,"rgb(0, 25, 0)"],\ [0.375,"rgb(0, 152, 0)"],[0.5,"rgb(44, 255, 0)"],[0.625,"rgb(151, 0, 0)"],\ [0.75,"rgb(255, 234, 0)"],[0.875,"rgb(255, 111, 0)"],[1,"rgb(255, 0, 0)"] data = [ go1.Scattergeo(lat=data1['Latitude'], lon=data1['Longitude'], text=data1['Name of State / UT'] + '\n' + 'Confirmed : ' + (data1['Total cases']) + '\n' + 'Deaths : ' + (data1['Deaths']), marker=dict(color=(data1['Active cases'] % 100) * 0.01, size=7, opacity=0.7)) ] fig = go1.Figure(data=data) fig.update_layout(title='World map-INDIA', height=700, mapbox_center={ "lat": 60.0902, "lon": 40.7129 }) return fig
def agg_map(self, report_df_target_col='reach', report_df_city_col='region', location_df_city_col='City', output_image='map.png', longitude='Longitude', latitude='Latitude', limit=7, scale=1.5): """Groups the report's data frame by city and aggregates over the target column and joins it with the locations assigned to each city. Outputs map's image.""" # report_df_target_col = The column that defines the size of the bubbles # report_df_city_col = location column in report_df # location_df_city_col = location column in location_df # output_image = destination address of map on local host # longitude = Name of the longitude column in location_df # latitude = Name of the latitude column in location_df # limit = Number of cities(bubbles) to appear on the map # scale = scale of the bubbles ### Group by report_df_city_col and aggregate # plotly.io.orca.config.executable = 'miniconda3/bin/orca' limited_report_df = self.report_df[[report_df_target_col, report_df_city_col]] report_df_agg = limited_report_df.groupby([report_df_city_col], as_index=False).agg('sum') report_df_agg.rename({report_df_city_col: location_df_city_col}, axis='columns', inplace=True) report_df_agg_merged = report_df_agg.merge(self.location_df, on=location_df_city_col, how='left') report_df_agg_merged.sort_values(by=[report_df_target_col], ascending=False, inplace=True) report_df_agg_merged.reset_index(drop=True, inplace=True) cities = [] number_of_bubbles_on_map = min(report_df_agg_merged.shape[0], limit) ### Add one bubble for each city on the map. The bubble size is proportional to the report_df_target_col entry for i in range(number_of_bubbles_on_map): df_sub = report_df_agg_merged.iloc[[i]] city = go.Scattergeo( locationmode='USA-states', lon=df_sub[longitude], lat=df_sub[latitude], marker=go.scattergeo.Marker( size=df_sub[report_df_target_col] / scale, line=go.scattergeo.marker.Line(width=0.5, color='rgb(40,40,40)'), sizemode='area' ), name='{} -- {}: {:,}'.format(df_sub[location_df_city_col].values[0], report_df_target_col, df_sub[report_df_target_col].values[0]) ) cities.append(city) ### Layout of the map layout = go.Layout( showlegend=True, geo=go.layout.Geo( scope='usa', projection=go.layout.geo.Projection(type='albers usa'), showland=True, landcolor='rgb(217, 217, 217)', subunitwidth=1, countrywidth=1, subunitcolor="rgb(255, 255, 255)", countrycolor="rgb(255, 255, 255)", ) ) fig = go.Figure(data=cities, layout=layout) fig.update_layout(legend=dict(x=0.82, y=0)) fig.write_image(output_image, scale=3)
def plotScatterOverTime(cluster_centers_list, weekCount): # plot articles as regular data over time scl = [[0, "rgb(5, 10, 172)"]] data = [] for i in range(weekCount): trace_points = go.Scattergeo( visible=False, type='scattergeo', showlegend=True, name='Articles: ' + cluster_centers_list['date_range'][i], #locationmode = 'USA-states', lon=cluster_centers_list[i]['points']['lon'], lat=cluster_centers_list[i]['points']['lat'], text=cluster_centers_list[i]['points']['topic'], mode='markers', marker=dict(size=8, opacity=0.8, reversescale=True, autocolorscale=True, symbol='square', line=dict(width=1, color='rgba(102, 102, 102)'), colorscale=scl, cmin=0, color=0, cmax=0)) data.append(trace_points) data[-1].visible = True steps = [] for i in range(weekCount): step = dict(method='restyle', args=['visible', [False] * len(data)], label=list(range(weekCount))) step['args'][1][i] = True # Toggle i'th trace to "visible" steps.append(step) sliders = [ dict(active=weekCount - 1, currentvalue={'prefix': 'Weeks Showing: '}, pad={'t': 1}, steps=steps) ] layout = dict( title='Scatter Plot Over Time', colorbar=True, showlegend=True, geo=dict( #scope='usa', #projection=dict( type='albers usa' ), showland=True, landcolor="rgb(250, 250, 250)", subunitcolor="rgb(217, 217, 217)", countrycolor="rgb(217, 217, 217)", countrywidth=0.5, subunitwidth=0.5), sliders=sliders) fig = dict(data=data, layout=layout) py.plot(fig, validate=False, filename='charts/Scatter-Time.html')
def geo_concentration_plot(selected_data): data = [] opacity_level = 0.8 MC_conc = selected_data['Microcystin (ug/L)'] # make bins b1 = selected_data[MC_conc <= USEPA_LIMIT] b2 = selected_data[(MC_conc > USEPA_LIMIT) & (MC_conc <= WHO_LIMIT)] b3 = selected_data[MC_conc > WHO_LIMIT] data.append( go.Scattergeo(lon=b1['LONG'], lat=b1['LAT'], mode='markers', text=b1["Body of Water Name"], visible=True, name="MC <= USEPA Limit", marker=dict(color="green", opacity=opacity_level))) data.append( go.Scattergeo(lon=b2['LONG'], lat=b2['LAT'], mode='markers', text=b2["Body of Water Name"], visible=True, name="MC <= WHO Limit", marker=dict(color="orange", opacity=opacity_level))) data.append( go.Scattergeo(lon=b3['LONG'], lat=b3['LAT'], mode='markers', text=b3["Body of Water Name"], visible=True, name="MC > WHO Limit", marker=dict(color="red", opacity=opacity_level))) layout = go.Layout(showlegend=True, hovermode='closest', title="Microcystin Concentration", geo=dict(scope='world', showframe=False, showcoastlines=True, showlakes=True, showland=True, landcolor="rgb(229, 229, 229)", showrivers=True)) fig = go.Figure(layout=layout, data=data) return fig
def map_chart(df, x, y, title,fname): df.head() br_tag = "'<br>"+y+"'" df['text'] = df[x] + br_tag + (df[y] / 1e9).astype(str) + ' billion' limits = [(0, 2), (3, 10), (11, 20), (21, 50), (50, 3000)] colors = ["rgb(0,116,217)", "rgb(255,65,54)", "rgb(133,20,75)", "rgb(255,133,27)", "lightgrey"] cities = [] scale = 10000000 for i in range(len(limits)): lim = limits[i] df_sub = df[lim[0]:lim[1]] city = go.Scattergeo( locationmode='USA-states', lon=df_sub['longitude'], lat=df_sub['latitude'], text=df_sub['text'], marker=go.scattergeo.Marker( size=df_sub[y] / scale, color=colors[i], line=go.scattergeo.marker.Line( width=0.5, color='rgb(40,40,40)' ), sizemode='area' ), name='{0} - {1}'.format(lim[0], lim[1])) cities.append(city) layout = go.Layout( title=go.layout.Title( text=title ), showlegend=True, geo=go.layout.Geo( scope='usa', projection=go.layout.geo.Projection( type='albers usa' ), showland=True, landcolor='rgb(217, 217, 217)', subunitwidth=1, countrywidth=1, subunitcolor="rgb(255, 255, 255)", countrycolor="rgb(255, 255, 255)" ) ) map = go.Figure(data=cities, layout=layout) # py.iplot(map, filename='d3-bubble-map-upb-exposure-by-state') path1 = 'images/' + fname + '.jpg' print(path1) path2 = 'images/' + fname + '.pdf' print(path2) path3 = 'images/' + fname + '.png' print(path3) pio.write_image(map, path1) pio.write_image(map, path2) pio.write_image(map, path3) return
def plot_state_airports(state): # print(state) codes = [ airport[1].replace('\n', '') for airport in get_airports(state) if get_loc(airport[1].replace('\n', '')) ] if not codes: return "<h1>Oops! There's no busy airport in this state.</h1>" locs = [get_loc(code) for code in codes] lat_vals = [float(loc[0]) for loc in locs] lon_vals = [float(loc[1]) for loc in locs] text_vals = [ query("SELECT name FROM Airports WHERE IAtA='{}'".format(code))[0][0] + " ({})".format(code) for code in codes ] center = (mean(lat_vals), mean(lon_vals)) lat_axis = [center[0] - 20, center[0] + 20] lon_axis = [center[1] - 20, center[1] + 20] layout = dict( title="Airports in {}".format(state), geo=dict( # scope='usa', projection=dict(type='albers usa'), showland=True, landcolor="rgb(235, 189, 52)", subunitcolor="rgb(17, 23, 31)", countrycolor="rgb(100, 137, 217)", showlakes=True, lakecolor="rgb(52, 128, 235)", showocean=True, oceancolor="rgb(52, 128, 235)", lataxis={'range': lat_axis}, lonaxis={'range': lon_axis}, center={ 'lat': center[0], 'lon': center[1] }, countrywidth=3, subunitwidth=3)) fig = go.Figure(data=go.Scattergeo(lon=lon_vals, lat=lat_vals, text=text_vals, mode='markers', marker_color='red', marker={ "symbol": "star", "size": 15 }, showlegend=False)) fig.update_layout(layout) return fig.to_html(fig, include_plotlyjs=True, full_html=True)
def maker_data_graph(self, data_top): """ Método responsável por preparar o dados para serem plotados no gráfico :param data_top: dados com os países e a quantidade de vagas :return: lista de países e valores """ countries = [country for country in data_top] values = [value for value in data_top.values()] latitudes, longitudes = self.get_countries_coordinates(countries) data_countries = pd.DataFrame({ "country": countries, "vacancy": values, "latitude": latitudes, "longitude": longitudes }) trace = go.Scattergeo(locationmode='ISO-3', lon=data_countries['longitude'], lat=data_countries['latitude'], text=data_countries['country'] + ' - N° Vagas: ' + data_countries['vacancy'].astype(str), marker=dict(size=data_countries['vacancy'] * 3, color='#e74c3c', line={ 'width': 0.8, 'color': '#2c3e50' }, sizemode='area')) data = [trace] layout = go.Layout( title='<b>Distribuição de vagas do Google pelo mundo</b>', titlefont={ 'family': 'Arial', 'size': 24 }, geo={ 'scope': 'world', 'projection': { 'type': 'equirectangular', 'scale': 1.1 }, 'showland': True, 'landcolor': '#2ecc71', 'showlakes': True, 'lakecolor': '#3498db', 'subunitwidth': 2, 'subunitcolor': "rgb(255, 255, 255)" }) return data, layout
def generar_mapa_importados(df_data): df_data_grouped = generar_cuenta_importados(df_data) fig = go.Figure() for i in range(len(df_data_grouped)): fig.add_trace( go.Scattergeo( lon=[ df_data_grouped['long'][i], df_data_grouped['end_long'][i] ], lat=[df_data_grouped['lat'][i], df_data_grouped['end_lat'][i]], mode='lines', line=dict(width=2 * (np.log(df_data_grouped['cuenta'][i]) / np.log(df_data_grouped['cuenta'].max())), color='#051C57'), opacity=1, )) fig.add_trace( go.Scattergeo(lon=df_data_grouped['long'], lat=df_data_grouped['lat'], text=df_data_grouped['texto'], hoverinfo="text", mode='markers', marker=dict( size=10, opacity=(np.log(df_data_grouped['cuenta']) / np.log(df_data_grouped['cuenta'].max())), color="#051C57"))) fig.update_layout( title_text='Procedencia de confirmados', showlegend=False, font=dict(family="Courier New, monospace", size=28, color="#7f7f7f"), geo=dict( scope='world', showland=True, landcolor='rgb(243, 243, 243)', countrycolor='rgb(204, 204, 204)', ), ) return fig
def update_map(top_ten): global df top_ten = pd.read_json(top_ten) top_ten_cy = top_ten[top_ten["Year"] == 2019] top_ten_cy = top_ten_cy.sort_values("final_score", ascending=False) #top_ten = df[df["City"].isin(top_ten_cy.head(n=10)["City"].values)] top_ten["place"] = "#0390d4" top_ten.sort_values("final_score", ascending=False, inplace=True) top_ten.reset_index(drop=True, inplace=True) city = top_ten[top_ten["Year"] == 2019].head(1).iloc[0]["City"] top_ten.loc[top_ten["City"] == city, "place"] = "#d6565f" coord_tf = df_coord[df_coord.index.isin(top_ten["City"].values)] top_ten_cy = top_ten_cy.reset_index(drop=True) coord_tf = pd.merge(coord_tf, top_ten, how='right', left_on="City", right_on="City") fig_map = go.Figure(data=go.Scattergeo( lon=coord_tf['lng'], lat=coord_tf['lat'], text=[ str(top_ten_cy[top_ten_cy["City"] == c].index.values[0] + 1) + "." + c for c in coord_tf['City'].values ], hoverinfo="text", mode='markers', marker=dict( size=7, color=coord_tf['place'], #coord_tf["final_score"] ))) fig_map.update_layout( margin=dict(l=0, r=0, t=0, b=0), dragmode=False, geo=dict( showland=True, scope="world", # can be updated when continent is landcolor="#DADADA", subunitcolor="rgb(255, 255, 255)", coastlinecolor="rgb(255, 255, 255)", countrycolor="rgb(255, 255, 255)", showlakes=True, lakecolor="rgb(255, 255, 255)", showsubunits=True, showcountries=True, framecolor="rgb(255, 255, 255)", #resolution = 50, countrywidth=0.1, )) return fig_map
def bubble_map(csvfile): df = pd.read_csv(csvfile,nrows=321) df.head() df['text'] = 'Wind Speed: ' + (df['wind speed']).astype(str) + '<br>Visibility: ' + (df['visibility']).astype(str) + '<br>Precipitation: ' + (df['precipitation']).astype(str) limits = [(0,6),(7,41),(42,92),(93,141),(142,320)] legends = [(73,79),(69,72),(63,69),(53,63),(2,53)] colors = ["red","yellow","green","blue","lightgrey"] airports1 = [] for i in range(len(limits)): lim = limits[i] leg = legends[i] df_sub = df[lim[0]:lim[1]] port = go.Scattergeo( locationmode = 'USA-states', lon = df_sub['lgn'], lat = df_sub['lat'], text = df_sub['text'], marker = go.scattergeo.Marker( size = df_sub['temperature']*4, color = colors[i], line = go.scattergeo.marker.Line( width=0.5, color='rgb(40,40,40)' ), sizemode = 'area' ), name = '{0} - {1} miles/hour'.format(leg[0],leg[1]) ) airports1.append(port) layout = go.Layout( title = go.layout.Title( text = "Today's wind speed and temperature at airports in US\nSize: Temperature\nColor: Wind Speed" ), showlegend = True, geo = go.layout.Geo( scope = 'usa', projection = go.layout.geo.Projection( type='albers usa' ), showland = True, landcolor = 'rgb(217, 217, 217)', subunitwidth=1, countrywidth=1, subunitcolor="rgb(255, 255, 255)", countrycolor="rgb(255, 255, 255)" ) ) fig = go.Figure(data=airports1, layout=layout) py.plot(fig, filename='airports-bubblemap',auto_open = True)
def plot_sites_for_state(state_abbr): lat_vals = [] lon_vals = [] text_vals = [] sites_list = get_sites_for_state(state_abbr) new_url = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?' params3 = {} params3['key'] = google_places_key params3['fields'] = 'geometry' params3['inputtype'] = 'textquery' for site in sites_list: params3['input'] = site.name + ' ' + site.type site_data = make_second_request_using_cache(new_url, params3) if len(site_data['candidates']) != 0: site_lat = site_data['candidates'][0]['geometry']['location'][ 'lat'] site_lon = site_data['candidates'][0]['geometry']['location'][ 'lng'] lat_vals.append(site_lat) lon_vals.append(site_lon) text_vals.append(site.name) min_lat = float(min(lat_vals)) max_lat = float(max(lat_vals)) min_lon = float(min(lon_vals)) max_lon = float(max(lon_vals)) lat_axis = [min_lat, max_lat] lon_axis = [max_lon, min_lon] layout = dict(title='National Parks in ' + state_abbr.upper(), geo=dict(scope='usa', projection=dict(type='albers usa'), showland=True, landcolor="rgb(250, 250, 250)", subunitcolor="rgb(100, 217, 217)", countrycolor="rgb(217, 100, 217)", lataxis={'range': lat_axis}, lonaxis={'range': lon_axis}, countrywidth=3, subunitwidth=3)) fig = go.Figure(data=go.Scattergeo( lon=lon_vals, lat=lat_vals, text=text_vals, mode='markers', marker_color='red', )) fig.update_layout(layout) fig.show()
def create_map(access_token=None, markers=None): df = pd.DataFrame(markers) try: df['lon'], df['lat'] = zip(*df.location) except AttributeError: return df = df.drop(columns=['location']) df = df.groupby([df.lon, df.lat, df.label], as_index=False)['value'].sum() scale = 4 data = [ go.Scattergeo(lon=df.lon, lat=df.lat, text=df.label + ": " + df.value.astype(str), name="asd", marker=dict(size=df.value / scale, color='#ff5d86', line=dict(width=0.5, color='#ff5d86'), sizemode='area')) ] layout = dict( # title = 'users by location', showlegend=False, autosize=True, margin=go.layout.Margin(l=0, r=0, b=0, t=0, pad=0), xaxis=dict(fixedrange=True), yaxis=dict(fixedrange=True), dragmode=False, font=dict(family="'AvenirNext', 'avenir next', sans-serif", size="13px"), hoverlabel=dict(bgcolor='#211228', bordercolor='#ffffff'), geo=dict(scope='world', projection=dict(type='Mercator'), showframe=False, showland=True, showcountries=True, showlakes=True, subunitcolor="#d5d5d5", subunitwidth=1, lakecolor="#ffffff", landcolor='#f9f9f9', countrycolor="#d5d5d5", countrywidth=1, automargin=False, coastlinecolor="#d5d5d5")) config = {'scrollZoom': False} return dcc.Graph(id='graph', figure=dict(data=data, layout=layout, config=config))
def plot_airport(code): loc = get_loc(code) if not loc: return "<h1>Oops! Data missing...</h1>" lat_vals = [float(loc[0])] lon_vals = [float(loc[1])] text_vals = [ query("SELECT name FROM Airports WHERE IAtA='{}'".format(code))[0][0] + " ({})".format(code) ] lat_axis = [lat_vals[0] - 20, lat_vals[0] + 20] lon_axis = [lon_vals[0] - 20, lon_vals[0] + 20] layout = dict( title=text_vals[0], geo=dict( # scope='usa', projection=dict(type='albers usa') if code not in INSULAR_AIRPORTS else dict(type='equirectangular'), showland=True, landcolor="rgb(235, 189, 52)", subunitcolor="rgb(17, 23, 31)", countrycolor="rgb(100, 137, 217)", showlakes=True, lakecolor="rgb(52, 128, 235)", showocean=True, oceancolor="rgb(52, 128, 235)", lataxis={'range': lat_axis}, lonaxis={'range': lon_axis}, center={ 'lat': lat_vals[0], 'lon': lon_vals[0] }, countrywidth=3, subunitwidth=3)) fig = go.Figure(data=go.Scattergeo(lon=lon_vals, lat=lat_vals, text=text_vals, mode='markers', marker_color='red', marker={ "symbol": "star", "size": 15 }, showlegend=False)) fig.update_layout(layout) # fig.show() return fig.to_html(fig, include_plotlyjs=True, full_html=True)
def create_map(df): data = [ go.Scattergeo( lon=df['long'], lat = df['lat'], mode="markers" , locationmode="USA-states", hovertext = df['text'] ) ] graphJSON = json.dumps(data,cls = plotly.utils.PlotlyJSONEncoder) return graphJSON
def town(): df = pd.read_csv(os.getcwd() + '/' + 'csv/city_rus.csv') df.head() df['text'] = df['name'] + '<br>Население ' + (df['pop'] / 1e3).astype(str) + ' тыс' limits = [(0, 1e4), (1e4 + 1, 1e5), (1e5 + 1, 5e5), (5e5 + 1, 1e6), (1e6 + 1, 1e8)] colors = ["blue", "green", "yellow", "orange", "red"] size = [10, 15, 20, 25, 30] cities = [] scale = 80000 for i in range(len(limits)): lim = limits[i] df_sub = df[df['pop'] >= lim[0]][df['pop'] <= lim[1]] city = go.Scattergeo(locationmode='ISO-3', lon=df_sub['lon'], lat=df_sub['lat'], text=df_sub['text'], marker=go.scattergeo.Marker( size=size[i], color=colors[i], line=go.scattergeo.marker.Line( width=0.5, color='rgb(40,40,40)'), sizemode='diameter'), name='{0} - {1}'.format(lim[0], lim[1])) cities.append(city) layout = go.Layout(title=go.layout.Title(text='Население'), showlegend=True, autosize=False, width=1500, height=1000, margin=dict(l=50, r=50, b=50, t=50, pad=4, autoexpand=True), geo=go.layout.Geo( scope='world', showland=True, landcolor='rgb(217, 217, 217)', subunitwidth=1, countrywidth=1, subunitcolor="rgb(255, 255, 255)", countrycolor="rgb(255, 255, 255)", showrivers=True, projection=dict(type='mercator'), )) return go.Figure(data=cities, layout=layout)
def graph_states(year="2015", compare="Wins_pct", state="Hawaii"): if year == '2015': year = 'fifteen' if year == '2016': year = 'sixteen' if year == '2017': year = 'seventeen' if year == '2018': year = 'eighteen' if year == '2019': year = 'nineteen' if year == "Last 5": year = "totals" conn = sqlite3.connect(DATABASE) cur = conn.cursor() cur.execute("select " + year + ".School, " + compare + ", latitude, longitude from " + year + " join locations on " + year + ".School = locations.School where state='" + state + "'") response = cur.fetchall() lats = [] lons = [] school = [] outcome = [] for x in response: school.append(x[0]) lats.append(x[2]) lons.append(x[3]) outcome.append(x[1]) color = [] for x in outcome: if x == "Basketball": color.append("Red") else: color.append("Blue") qdf = pd.DataFrame(list(zip(lats, lons, school, color)), columns=['lat', 'lon', 'school', 'color']) fig = go.Scattergeo( lat=qdf['lat'], lon=qdf['lon'], text=qdf['school'], mode='markers', locationmode='USA-states', marker_color=qdf['color'], ) data = [fig] graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder) return graphJSON
def add_storage_to_map(self, types, attribute): storage_idx = self.net.storage_units[self.net.storage_units.type.isin( types)].index if len(storage_idx) == 0: print( f"Warning: There is no generator of type {types} in the model." ) raise ValueError all_xs = self.net.storage_units.loc[storage_idx, "x"].values all_ys = self.net.storage_units.loc[storage_idx, "y"].values map_coords = [ min(all_xs) - 5, max(all_xs) + 5, min(all_ys) - 2, max(all_ys) + 2 ] title = f"{attribute} for {','.join(types)}" fig = get_map_layout(title, map_coords) if attribute in self.net.storage_units_t.keys(): values = self.net.storage_units_t[attribute][storage_idx].mean() else: values = self.net.storage_units.loc[storage_idx, attribute].values colors = np.array([ self.tech_colors[tech_type] for tech_type in self.net.storage_units.loc[storage_idx].type.values ]) colors[[i for i in range(len(colors)) if values[i] == 0]] = 'black' max_value = np.max(values) if max_value == 0: max_value = 1 # Prevents cases where there is no installed capacity at all fig.add_trace( go.Scattergeo( mode="markers", lat=all_ys, lon=all_xs, text=[ f"{storage_idx[i]} {values[i]}" for i in range(len(values)) ], hoverinfo='text', marker=dict(size=10 + 40 * np.log(1 + values / max_value), color=colors), )) return fig
def update_map(choice): title = choice.replace('_', ' ').capitalize() fig = go.Figure() scales = { 'total_cases': 1000, 'total_deaths': 200, 'total_tests_per_thousand': 0.3 } colors = { 'total_cases': '#B80C09', 'total_deaths': '#040F16', 'total_tests_per_thousand': '#01BAEF' } fig.add_trace( go.Scattergeo( lon=df_map['longitude'], lat=df_map['latitude'], text=df_map['name'], customdata=df_map, hovertemplate='%{text} <br>' + "Number of tests per 1k people %{customdata[3]:,.2f} <br>" + "Number of total cases %{customdata[1]:,.0f}<br>" + "Number of deaths %{customdata[2]:,.0f}", marker=dict( size=df_map[choice] / scales[choice] + 5, sizeref=1, sizemin=0, #colorscale=[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']], autocolorscale=False, color=colors[choice], line_color='rgb(40,40,40)', line_width=0.5, sizemode='area', opacity=0.5))) fig.update_layout(title_text=f'Number of {title}', margin=dict(t=30, b=0, l=0, r=0), geo=dict( scope='world', showcountries=True, showframe=False, showcoastlines=True, landcolor="rgb(229, 229, 229)", countrycolor="white", coastlinecolor="white", )) return fig
def render_temp(df, state, city): city_of_interest = df[(df['state_name_x'] == state) & (df['city'] == city)] index = city_of_interest.index[0] N = 50 colorscale = ['rgb'+str(i) for i in sns.color_palette("icefire", n_colors=N)] endpts = list(np.linspace(df['LTM_mean_temp'].min(), df['LTM_mean_temp'].max(), N-1)) text = [str(df['LTM_mean_temp'].iloc[i])+', '+df['city'].iloc[i]+', '+df['state_name_x'].iloc[i] for i in range(len(df))] size = [10 for i in range(len(text))] size[index] = 55 fig = go.Figure() fig.add_trace( go.Scattergeo( locationmode = 'USA-states', lon = df['lng'], lat = df['lat'], text = text, mode = 'markers', marker = dict( size = size, color=df['LTM_mean_temp'], opacity=0.75, colorscale = 'icefire', colorbar = dict( titleside = "right", outlinecolor = "rgba(68, 68, 68, 0)", ticks = "outside", showticksuffix = "last",)))) fig.update_layout( hoverlabel=dict( bgcolor="white", font_size=16, font_family="Rockwell" ), title = 'USA by Long Term Mean Temperature (F°)', showlegend = False, geo = dict( scope = 'north america', projection_type = 'albers usa', showland = True, landcolor = 'rgb(230,230,230)', countrycolor = 'rgb(204, 204, 204)'), width = 960*3/4, height = 700*3/4) return dcc.Graph(id = "temp-component", figure = fig, className="center-align")