예제 #1
0
def create_figure3(dff):
    
    fig3 = px.line_geo(dff, locations="ISO", 
                      #color="Continent", 
                      projection="orthographic", 
                     width=600, height=600)
    fig3.update_geos(projection_rotation=dict(lon=-42, lat=69, roll=0),)
    
    fig3.update_layout(margin={"r":0,"t":0,"l":100,"b":10})
    return fig3
예제 #2
0
def UpdateGraph(lap_ids: List[int],
                point_values: List[Text]) -> List[dcc.Graph]:
    if not isinstance(point_values, list):
        point_values = [point_values]
    if lap_ids:
        graphs = []
        laps_data = queries.GetLapsData(lap_ids, point_values)
        for point_value in point_values:
            figure_data = laps_data
            title = point_value
            # Copied so that time_delta can redefine without breaking other graphs.
            if point_value == 'time_delta':
                figure_data = laps_data.copy()
            if point_value == 'racing_line':
                graph_type = 'map'
                fig = px.line_geo(
                    laps_data,
                    title=title,
                    lat='lat',
                    lon='lon',
                    color='lap_id',
                    fitbounds='locations',
                )
            else:
                if point_value == 'time_delta':
                    if len(lap_ids) < 2:
                        continue  # Need at least two laps to make a comparison.
                    figure_data = queries.GetTimeDelta(lap_ids)
                    title = 'time_delta vs first selected lap (lap_id: %s)' % lap_ids[
                        0]
                graph_type = 'graph'
                fig = px.line(figure_data,
                              title=title,
                              x='elapsed_distance_m',
                              y=point_value,
                              color='lap_id',
                              hover_data=['lap_id', 'lap_number', point_value])
                fig.update_xaxes(showspikes=True)
                fig.update_yaxes(fixedrange=True)
                fig.update_layout(hovermode='x unified')
            graph = dcc.Graph(
                {
                    'type': graph_type,
                    'index': point_values.index(point_value)
                },
                figure=fig,
                style={
                    'display': 'inline-grid',
                    'width': '50%'
                })
            graphs.append(graph)
        return graphs
    # Empty line when no rows have been selected.
    return [dcc.Graph(figure=px.line())]
    def plot(self, json_fp: Path):
        with open(str(json_fp)) as json_file:
            data = json.load(json_file)
            trajectory_dict = data["prediction"][1]["trajectory"]
            df = pd.DataFrame.from_dict(trajectory_dict)

            # Convert to datetime format. Have to remove last 3 decimal places for the parser to work
            df['datetime'] = df['datetime'].str.slice(0, -4)
            df['datetime_type'] = pd.to_datetime(df['datetime'])

            # Hacky section to calculate solar elevation for display.
            # TODO: convert this into more pandas/numpy form.
            ts_list = df["datetime_type"].dt.to_pydatetime().tolist()

            solar_elevation_list = []
            for i in range(len(ts_list)):
                elevation = get_altitude(
                    longitude_deg=df["longitude"][i],
                    latitude_deg=df["latitude"][i],
                    when=ts_list[i].replace(tzinfo=timezone.utc))
                solar_elevation_list.append(elevation)

            df["solar_elevation"] = solar_elevation_list

            fig = px.line_geo(
                df,
                lat="latitude",
                lon="longitude",
                hover_data=["altitude", "datetime", "solar_elevation"],
                projection="orthographic",
            )

            #fig.update_layout(mapbox_style="open-street-map")
            fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
            fig.update_geos(resolution=110, showcountries=True)
            return fig
예제 #4
0
    st.write("Les cas importés, ayant ensuite crée des cas contact, proviennent des pays suivants:")

    ch3 = alt.Chart(df.dropna(subset=['Source/Voyage'])).mark_bar().encode(
    	x = 'Source/Voyage:N',
        y=alt.Y('count()', title='Nombre de patients')
    ).properties(title="Provenance des malades", height=300, width=700)

    st.write(ch3)

    # Interactive Map
    st.write("Visualisation interactive de la provenance des cas de COVID-19:")

    df3 = px.data.gapminder().query("year == 2007")
    df2 = df3[(df3['country']=="Italy") | (df3['country']=="Senegal") | (df3['country']=="United Kingdom") | (df3['country']=="France") | (df3['country']=="Spain")]

    fig = px.line_geo(df2, locations="iso_alpha",
                      projection="orthographic")

    st.plotly_chart(fig)

    # V. Population
    st.markdown("---")
    st.subheader("Population touchée")
    st.write("Les chiffres présentés ci-dessous tiennent compte des publication du Ministère de la Santé et de l'Action Sociale. Certaines données sont manquantes, et nous n'affichons que les valeurs connues à ce jour.")

    st.write("1. L'age moyen des patients est de ", np.mean(df['Age'].dropna()), " ans")

    ch = alt.Chart(df).mark_bar().encode(
    	x = 'Age:Q',
        y=alt.Y('count()', title='Nombre de patients')
    ).properties(title="atu aji wop gii ", height=300, width=700)
import plotly.express as px

fig = px.line_geo(lat=[51.555051, 55.753215, 28.613506],
                  lon=[46.013428, 37.622504, 77.207917],
                  projection="orthographic")
예제 #6
0
    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",
)
fig.write_html(os.path.join(dir_name, "line_geo.html"))

import plotly.express as px

gapminder = px.data.gapminder()
fig = px.choropleth(
    gapminder,
    locations="iso_alpha",
    color="lifeExp",
    hover_name="country",
    animation_frame="year",
    range_color=[20, 80],
)
예제 #7
0
fig.show()
'''Map projections can be rotated using the layout.geo.projection.rotation attribute, 
and maps can be translated using the layout.geo.center attributed, as well as truncated to
 a certain longitude and latitude range using the layout.geo.lataxis.range and layout.geo.lonaxis.range.
 '''
fig = go.Figure(go.Scattergeo())
fig.update_geos(center=dict(lon=-30, lat=-30),
                projection_rotation=dict(lon=30, lat=30, roll=30),
                lataxis_range=[-50, 20],
                lonaxis_range=[0, 200])
fig.update_layout(height=300, margin={"r": 0, "t": 0, "l": 0, "b": 0})
fig.show()
'''To automatically set the boundaries of the map according to the data to be plotted...fitbounds'''
import plotly.express as px

fig = px.line_geo(lat=[0, 15, 20, 35], lon=[5, 10, 25, 30])
fig.update_geos(fitbounds="locations")
fig.update_layout(height=300, margin={"r": 0, "t": 0, "l": 0, "b": 0})
fig.show()
'''The available scopes are: 'world', 'usa', 'europe', 'asia', 'africa', 'north america', 'south america'.
'''
fig = go.Figure(go.Scattergeo())
fig.update_geos(visible=False,
                resolution=50,
                scope="north america",
                showcountries=True,
                countrycolor="Black",
                showsubunits=True,
                subunitcolor="Blue")
fig.update_layout(height=300, margin={"r": 0, "t": 0, "l": 0, "b": 0})
fig.show()
예제 #8
0
import plotly.express as px
gapminder = px.data.gapminder().query("year == 2007")
fig = px.line_geo(
    gapminder,
    locations="iso_alpha",
    color="continent",  # "continent" is one of the columns of gapminder 
    projection="orthographic")
fig.show()
예제 #9
0
import plotly.graph_objects as go
fig = go.Figure(go.Densitymapbox(lat=quakes.Latitude, lon=quakes.Longitude, z=quakes.Magnitude,
                                 radius=10))
fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=180)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()


# In[ ]:


import plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.line_geo(df, locations="iso_alpha",
                  color="continent", # "continent" is one of the columns of gapminder
                  projection="orthographic")
fig.show()


# In[ ]:


import plotly.graph_objects as go
import pandas as pd

df_airports = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
df_airports.head()

df_flight_paths = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_aa_flight_paths.csv')
df_flight_paths.head()
예제 #10
0
px.scatter_geo(gapminder, # 数据集
locations="iso_alpha",  # 配和color显示颜色
color="continent",  # 颜色的字段显示
hover_name="country",  # 悬停数据
size="pop",  # 大小
animation_frame="year"  # 数据联动变化的选择
#,projection="natural earth"   # 去掉projection参数
)


# In[14]:


fig = px.line_geo(
  gapminder,  # 数据集
  locations="iso_alpha",  # 配合和color显示数据
  color="continent",  # 颜色
  projection="orthographic")   # 球形的地图
fig.show()


# In[15]:


iris = px.data.iris()


# In[16]:


fig = px.scatter(
예제 #11
0
parser.add_argument('csv_file', help="name of the csv file serving as input")
parser.add_argument('-f',
                    '--format',
                    choices=['line', 'scatter', 'animation'],
                    default='line',
                    help="format of the map")
parser.add_argument('map_file', help="name of the output html file")

args = parser.parse_args()

df = pd.read_csv(args.csv_file, parse_dates=True)

if args.format == 'line':
    fig = px.line_geo(df[df['stadt_latitude'] != None],
                      lat='stadt_latitude',
                      lon='stadt_longitude',
                      scope='europe',
                      text='Stadt',
                      hover_data=['Anzahl Stadt'])
elif args.format == 'scatter':
    fig = px.scatter_geo(df,
                         lat='Latitude',
                         lon='Longitude',
                         scope='europe',
                         text='Ort',
                         hover_data=['Datum', 'Ereignis'])
#  elif args.format == 'bubble':
#      fig = px.scatter_geo(df, lat='Latitude', lon='Longitude', scope='europe',
#                        text='Ort', hover_data=['Datum', 'Ereignis'], size='')
elif args.format == 'animation':
    fig = px.scatter_geo(df,
                         lat='Latitude',
예제 #12
0
def view_edges_network(edges):
    """ Method to show edges (roads) of a network

    Args:
        edges (dataframe): Dataframe from networkx analysis of a graph for edges.
    """
    lats = []
    lons = []
    names = []
    thickness = []
    print("edges are ", len(edges))
    thousands_counter = 0
    for feature, name, traff in zip(edges.geometry, edges.name, edges.traffic):
        if isinstance(feature, shapely.geometry.linestring.LineString):
            linestrings = [feature]
        elif isinstance(feature,
                        shapely.geometry.multilinestring.MultiLineString):
            linestrings = feature.geoms
        else:
            continue
        for linestring in linestrings:
            x, y = linestring.xy
            lats = np.append(lats, y)
            lons = np.append(lons, x)
            names = np.append(names, [name] * len(y))
            thickness = np.append(thickness, [traff] * len(y))
            lats = np.append(lats, None)
            lons = np.append(lons, None)
            names = np.append(names, None)
            thickness = np.append(thickness, None)
            thousands_counter += 1
        if thousands_counter % 1000 == 0:
            print(thousands_counter)

    colors = thickness  #map_traffic_to_color(thickness)
    colors = np.array(colors)
    colors[colors == None] = 0  # make none values go
    colors = colors.astype(int)
    colors = colors / 10000000

    fig = px.line_geo(lat=lats,
                      lon=lons)  #, color=colors) #, hover_name=names)
    fig.add_trace(
        go.Scattermapbox(
            lon=lons,
            lat=lats,
            mode='lines+markers',
            marker=dict(
                size=0,
                showscale=True,
                colorscale='armyrose',  #[[0, 'green'], [1, 'red']],
                cmin=0,
                cmax=max(colors)),
        ))
    # fig.add_trace(
    #     go.Scattermapbox(
    #         lon = lons,
    #         lat = lats,
    #         mode='lines',
    #         line={'color':'green'},
    #     )
    # )
    fig.update_layout(margin={
        'l': 0,
        't': 0,
        'b': 0,
        'r': 0
    },
                      mapbox={
                          'center': {
                              'lon': 10,
                              'lat': 10
                          },
                          'style': "stamen-terrain",
                          'center': {
                              'lon': -20,
                              'lat': -20
                          },
                          'zoom': 1
                      })
    fig.show()
예제 #13
0
pd.set_option('display.max_columns', 150)
pd.set_option('display.max_rows', 150)

#%%
import plotly.express as px

import plotly.io as pio
pio.renderers

#%%
df = px.data.gapminder().query("year == 2007")
df.head()

#%%
fig = px.line_geo(df, locations="iso_alpha", color="continent", 
                  projection="orthographic")
fig.show()
fig.show(renderer = 'firefox')

#%%
#%%
import plotly.graph_objects as go

df_airports = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
df_airports.head()

df_flight_paths = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_aa_flight_paths.csv')
df_flight_paths.head()

#%%
fig = go.Figure()
예제 #14
0
파일: ISS_pos.py 프로젝트: elashrry/ISS_pos
def new_data(url):
    df = pd.read_json(url)
    df['lon'] = df.loc['longitude', 'iss_position']
    df['lat'] = df.loc['latitude', 'iss_position']
    df.reset_index(drop=True, inplace=True)
    df.drop(['iss_position', 'message'], axis=1, inplace=True)
    df.drop(0, axis=0, inplace=True)
    return df


url = 'http://api.open-notify.org/iss-now.json'
df = new_data(url)  # starting point

fig = px.line_geo(df,
                  lat='lat',
                  lon='lon',
                  title='Where is ISS Now',
                  projection='natural earth')
app = dash.Dash(__name__, update_title=None)  # remove "Updating..." from title
app.layout = html.Div(
    [dcc.Graph(id='graph', figure=fig),
     dcc.Interval(id="interval")])


@app.callback(Output('graph', 'extendData'),
              [Input('interval', 'n_intervals')])
def add_data(n_intervals):
    df = new_data(url)
    return {'lon': [df['lon']], 'lat': [df['lat']]}

예제 #15
0
    marker=dict(
        size=4,
        color=h_sol,
        colorscale='Viridis',
    ),line=dict(
        color='darkblue',
        width=2
    )
))
fig.show()


# %%
import plotly.express as px

fig = px.line_geo(lat=28.5971-theta_sol/pi*180, lon=-80.6833-phi_sol/pi*180, )
# fig.update_geos(fitbounds="locations")
# fig.update_layout(height=300, margin={"r":0,"t":0,"l":0,"b":0})
# fig.update_geos(projection_type="orthographic")
fig.add_scattergeo(lat=[28.5971], lon=[-80.6837], text="Kennedy Space Center Shuttle Landing Facility")
fig.update_geos(projection_type="orthographic",
    resolution=50,
    showcoastlines=True, coastlinecolor="RebeccaPurple",
    showland=True, landcolor="LightGreen",
    showocean=True, oceancolor="LightBlue",
    showlakes=False, lakecolor="Blue",
    showrivers=False, rivercolor="Blue"
)
fig.update_layout(height=300, margin={"r":0,"t":0,"l":0,"b":0})

fig.show()