コード例 #1
0
ファイル: plot.py プロジェクト: covlllp/farm_trails
def plot_fig():
    df = get_trail_paths()

    fig = px.line_mapbox(data_frame=df,
                         lat="lat",
                         lon="lon",
                         color_discrete_sequence=['red'],
                         line_group="hike",
                         center={
                             "lon": constants.CENTER_LONGITUDE,
                             "lat": constants.CENTER_LATITUDE
                         },
                         zoom=constants.MAP_ZOOM)
    fig.update_layout(
        mapbox_style="white-bg",
        mapbox_layers=[{
            "below":
            'traces',
            "sourcetype":
            "raster",
            "source": [
                "https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"
            ]
        }])
    fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
    return fig
コード例 #2
0
def updateGapHover(hoverData, whichGap, whichMap):
    plk = int(hoverData['points'][0]['customdata'][0])
    usegap = allGaps.loc[allGaps.POLYGON == whichGap, :]
    usegapsmall = usegap.loc[usegap.portion == plk, :]

    if whichMap == "sat":
        color_discrete_lks = color_discrete_lks_st
    elif whichMap != 'sat':
        color_discrete_lks = color_discrete_lks_ns

    fig = px.line_mapbox(
        usegapsmall,
        lon='lon',
        lat='lat',
        zoom=18,
        color='POLYGON',
        color_discrete_map=color_discrete_lks,
        width=50,

        #hover_data = {'portion'}
    )
    fig.update_layout(
        #autosize=True,
        width=800,
        height=800,
        showlegend=False,
    )
    fig.update_traces(line=dict(width=4))

    if whichMap == "sat":
        fig.update_layout(mapbox_style="satellite-streets", )

    return (fig)
コード例 #3
0
    def RenderToMap(self):
        self.dataframe = pd.DataFrame(self.listofrows,
                                      columns=["name", "lat", "lon", "time"])

        fig = px.line_mapbox(self.dataframe,
                             lat="lat",
                             lon="lon",
                             hover_name="name",
                             hover_data=["lat", "lon", "time"],
                             color="name",
                             title="Ocean Flow Simulation",
                             zoom=3,
                             height=900,
                             width=1600)

        fig.update_layout(mapbox_style="open-street-map",
                          mapbox_zoom=4,
                          mapbox_center_lat=36.9,
                          margin={
                              "r": 0,
                              "t": 0,
                              "l": 0,
                              "b": 0
                          },
                          legend=dict(
                              yanchor="top",
                              y=0.99,
                              xanchor="left",
                              x=0.01,
                          ))

        fig.show()
コード例 #4
0
def imprimeMapa(CiudadesViajadas):

    listaOrdenada = []
    dfCapitales = pd.read_csv(
        'C:/Users/crist/Desktop/Facultad/Algoritmos Geneticos/TPs/TP 3/provincias.csv'
    )
    listaCapitales = dfCapitales.values.tolist()
    for i in CiudadesViajadas:
        listaOrdenada.append(listaCapitales[i])
        fig = px.line_mapbox(listaOrdenada,
                             lat=1,
                             lon=2,
                             zoom=3,
                             width=1000,
                             height=900)
        fig.update_layout(mapbox_style="stamen-terrain",
                          mapbox_zoom=3.8,
                          mapbox_center_lat=-40,
                          margin={
                              "r": 0,
                              "t": 0,
                              "l": 0,
                              "b": 0
                          })
    fig.show()
コード例 #5
0
ファイル: display.py プロジェクト: LucasMagnana/bikesharing
def display(dfdisplay,
            n=75,
            line_group="route_num",
            color=None,
            filename=None):
    """
    Display a dataframe of gps points on a mapbox map.
    Parameters
    ----------
    df or str : pandas' DataFrame with columns=['lat', 'lon', 'route_num'] or the name of a file containing one
        Dataframe to display or the file where it is located
    n : int, optional
        Number of routes to display
    line_group : str, optional
        Dataframe's attribute used to differenciate routes
    color : str, optional
        Dataframe's attribute used to color routes
    """
    if (type(dfdisplay) == str):  #if df is a file location
        with open(dfdisplay, 'rb') as infile:
            n += 1
            dfdisplay = pickle.load(
                infile)  #open the file to load the dataframe
            dfdisplay = dfdisplay[dfdisplay[line_group] < n]
    fig = px.line_mapbox(dfdisplay,
                         lat="lat",
                         lon="lon",
                         line_group=line_group,
                         color=color,
                         zoom=11)
    fig.show()
    if (filename != None):
        fig.write_image(filename)
コード例 #6
0
def make_map_table_pair(df):
    to_map = df[df['status'] == 'Correct']
    fig = px.line_mapbox(to_map, lat='latitude', lon='longitude')
    fig.update_layout(mapbox_style='carto-positron')
    graph = dcc.Graph(figure=fig)
    table = make_table(df)
    return html.Div(children=[graph, table])
コード例 #7
0
def update_year_slider(slider):
    dff = filter_dataframe(df, slider)

    fig = px.line_mapbox(dff, lat="lat",
                         lon="lon",
                         color="id"
                         )
    return fig
コード例 #8
0
    def map_figure(self,
                   df: pd.DataFrame,
                   highlight_col: Optional[str] = None,
                   highlight_vals: Optional[List[int]] = None,
                   figure: Optional[go.Figure] = None,
                   **kwargs) -> go.Figure:
        """Generate the map figure showing an activity's route, from
        the DataFrame containing its points data.

        `highlight_col` specifies what column in the DataFrame to refer
        to when highlighting certain parts of the route, and
        `highlight_vals` specifies what values of that column to
        highlight.
        """
        # TODO:  More helpful hover text
        if figure:
            fig = go.Figure(figure)
        else:
            # TODO: Calculate zoom more intelligently
            fig = px.line_mapbox(df,
                                 lat="latitude",
                                 lon="longitude",
                                 zoom=12,
                                 **kwargs)
            fig.update_layout(mapbox_style="open-street-map",
                              margin={
                                  "r": 0,
                                  "t": 0,
                                  "l": 0,
                                  "b": 0
                              },
                              showlegend=False)
        if (highlight_col is not None) and (highlight_vals is not None):
            traces = [fig.data[0]]
            for trace in fig.data:
                try:
                    tn_int = int(trace.name)
                except (AttributeError, ValueError):
                    # Trace has no attribute "name", or its name can't be converted to an int
                    continue
                if tn_int in highlight_vals:
                    traces.append(trace)
                    highlight_vals.remove(tn_int)
            fig.data = traces

            for v in highlight_vals:
                data = df[df[highlight_col] == v]
                fig.add_trace(
                    go.Scattermapbox(
                        mode='lines',
                        lat=data['latitude'],
                        lon=data['longitude'],
                        marker={'color': 'red'},
                        name=v,
                        hoverinfo='text',
                        hovertext=data['time'].dt.strftime('%H:%M:%S')))
        return fig
コード例 #9
0
def plot_pipelines(df):
    color = 'rgb(100,100,100)'
    trace = px.line_mapbox(df,
                           lat="lat",
                           lon="lon",
                           color='type',
                           color_discrete_map={'pipeline': color},
                           custom_data=['type', 'name'],
                           hover_name='name')
    trace.update_traces(mode='markers+lines', marker={'opacity': 0})
    return trace.data
コード例 #10
0
def update_map_graph(track):
    if track == "track A":
        dff = df
    else:
        dff = df_2
    fig_map = px.line_mapbox(dff, lon=dff['lon'], lat=dff['lat'], custom_data=['ballast_water', 'fuel_rem',
                                                                               'grey_water', 'fresh_water', 'waste',
                                                                               'lubricant', 'CO2', 'fuel_con'], zoom=2)
    fig_map.update_layout(mapbox_style="stamen-terrain", mapbox_zoom=2, mapbox_center_lat=61,
                          margin={"r": 0, "t": 0, "l": 0, "b": 0})
    return fig_map
コード例 #11
0
def main():

    stations = pd.read_csv("../data/tube_stations.csv")
    print(stations)
    print("This takes a few minutes to run. Calculating...")
    manager = pywrapcp.RoutingIndexManager(len(stations), 1, 0)
    routing = pywrapcp.RoutingModel(manager)

    @functools.lru_cache(maxsize=None)
    def distance_callback(from_index, to_index):
        frm = stations.iloc[manager.IndexToNode(from_index)]
        to = stations.iloc[manager.IndexToNode(to_index)]
        return geodesic((frm["Latitude"], frm["Longitude"]),
                        (to["Latitude"], to["Longitude"])).meters

    transit_callback_index = routing.RegisterTransitCallback(distance_callback)

    # Define cost of each arc.
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # Setting first solution heuristic.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)

    # Solve the problem.
    solution = routing.SolveWithParameters(search_parameters)

    if solution:
        print(distance_callback.cache_info())
        route, distance = get_route(manager, routing, solution)
        print(f'Distance = {distance}')
        routed_stations = stations.iloc[route, :]
        print(routed_stations)
        fig = px.line_mapbox(routed_stations,
                             lat="Latitude",
                             lon="Longitude",
                             text="Name",
                             height=1000)
        fig.update_layout(mapbox_style="stamen-terrain",
                          mapbox_zoom=10,
                          margin={
                              "r": 0,
                              "t": 0,
                              "l": 0,
                              "b": 0
                          })
        fig.show()
コード例 #12
0
def update_polyLeak(whichPolygon,whichMap):
    usedat = allLeaks.loc[allLeaks.POLYGON == whichPolygon,:]
    
    if whichMap == "sat":
        color_discrete_lks = color_discrete_lks_st
    elif whichMap != 'sat':
        color_discrete_lks = color_discrete_lks_ns
        
        
    usepoly = allPoly.loc[allPoly.POLYGON == whichPolygon,:]
    usepoly2 = usepoly.loc[usepoly.portion == 3,:]
    if whichPolygon == "P5" or whichPolygon == "P58" or whichPolygon == "P59":
            usepoly2 = usepoly.loc[usepoly.portion == 1,:]

    fig = px.line_mapbox(
        usepoly2,
        lon = 'lat',
        lat = 'lon',
        zoom = 12,
        color = 'POLYGON',
        color_discrete_map=color_discrete_map_st

        )
    if usedat.shape[0]!=0:
        fig2 = px.scatter_mapbox(usedat, lat="Latitude", lon="Longitude",  
                      color = 'POLYGON', color_discrete_map = color_discrete_lks, size_max=15, zoom=11,
                      hover_data = {'PolyLK'})
        fig.add_trace(fig2.data[0])
        
    fig.update_layout(
        autosize=True,
        width = 800,
        height = 800,
        showlegend = False
        )

    fig.update()
    if whichMap == "sat":
        fig.update_layout(
            mapbox_style="satellite-streets",
 )
    
    
    return fig
コード例 #13
0
def update_map(activity):
    
    if activity is None:
        raise PreventUpdate
           
    else:

        filtered_df = df[df['startTime'] == activity]
        
        if filtered_df['samples.recordedRoute'].isnull().values.any():
            
            return px.scatter(x=['Not available'], y=['Not available'], title='Map', template='plotly_dark')
        
        else:
            route_df = pd.json_normalize(data=filtered_df.iloc[0]['samples.recordedRoute'], max_level=1)
            map_activ = px.line_mapbox(route_df, lat="latitude", lon="longitude", title='Map', 
                                          mapbox_style='carto-positron', zoom=12, template='plotly_dark')
            
            return map_activ
コード例 #14
0
ファイル: chart_map.py プロジェクト: aletuf93/logproj
def createFigureOptimalPoints(D_res_optimal, latCol, lonCol, descrCol):
    #D_res is a dataframe with flows defined by the function calculateOptimalLocation
    #latCol is a string with column name for latitude
    #lonCol is a string with column name for longitude
    #descrCol is a string with column name for node description

    # define the optimal location
    fig_optimal = px.line_mapbox(
        D_res_optimal,
        lat=latCol,
        lon=lonCol,
        #animation_frame="YEAR",
        hover_name=descrCol,
        #mode = 'lines'
        #color='COLOR',
        #color_continuous_scale='Inferno',
    )
    fig_optimal.update_layout(mapbox_style="open-street-map")
    return fig_optimal
コード例 #15
0
def updateGapHover(hoverData,whichGap,whichMap):
    plk = int(hoverData['points'][0]['customdata'][0])
    usegap = allGaps.loc[allGaps.POLYGON == whichGap,:]
    usegapsmall = usegap.loc[usegap.portion==plk,:]
    if whichMap == 'sat':
        color_discrete_map = {'P1': 'rgb(255,0,0)', 'P2': 'rgb(255,0,0)', 'P3': 'rgb(255,0,0)',
                          'P4': 'rgb(255,0,0)','P5': 'rgb(255,0,0)','P58': 'rgb(255,0,0)','P59': 'rgb(255,0,0)'}
        color_discrete_lks= {'P1': 'rgb(255,255,255)', 'P2': 'rgb(255,255,255)', 'P3': 'rgb(255,255,255)',
                          'P4': 'rgb(255,255,255)','P5': 'rgb(255,255,255)','P58': 'rgb(255,255,255)','P59': 'rgb(255,255,255)'}
    
    elif whichMap != 'sat':
        color_discrete_lks= {'P1': 'rgb(0, 0, 99)', 'P2': 'rgb(0, 0, 99)', 'P3': 'rgb(0, 0, 99)',
                          'P4': 'rgb(0, 0, 99)','P5': 'rgb(0, 0, 99)','P58': 'rgb(0, 0, 99)','P59': 'rgb(0, 0, 99)'}

    
    fig = px.line_mapbox(usegapsmall,
        lon = 'lon',
        lat = 'lat',
        zoom = 18,
        color = 'POLYGON',
        color_discrete_map=color_discrete_lks,
        width = 50
        #hover_data = {'portion'}
        )
    fig.update_layout(
     #autosize=True,
     width = 800,
     height = 800,
     showlegend = False,
   
    )
            
      
    if whichMap == "sat":
       fig.update_layout(
           mapbox_style="satellite-streets",
           )

    return(fig)
コード例 #16
0
ファイル: app.py プロジェクト: vo3xel/imu-vis
def create_map_figure(filename):
    data_frame = df[filename]
    df_map = data_frame.query('sensor_setup_id == 7 | sensor_setup_id == 8')
    df_map = df_map.pivot(index='timestamp', columns='sensor_setup_id')
    df_map = df_map.reset_index()
    df_map.columns = ['timestamp', 'lat', 'lon']
    fig_map = px.line_mapbox(df_map,
                             lat='lat',
                             lon='lon',
                             zoom=15,
                             height=600,
                             template=tpl)
    fig_map.update_layout(mapbox_style="dark",
                          mapbox_zoom=15,
                          mapbox_center_lat=df_map.loc[0, 'lat'],
                          mapbox_center_lon=df_map.loc[0, 'lon'],
                          margin={
                              "r": 0,
                              "t": 0,
                              "l": 0,
                              "b": 0
                          })
    return fig_map
コード例 #17
0
ファイル: shengassignment2.py プロジェクト: ishengy/COVID19
                      "b": 0
                  })

fig.show()

# In[6]:

f.write('Problem 1-1 Visuals Generated \n')

# # Problem 1-2

# In[7]:

daegu = patientroute[patientroute['province'] == 'Daegu']
route_fig = px.line_mapbox(daegu,
                           lat='latitude',
                           lon='longitude',
                           color='patient_id')

route_fig.update_layout(mapbox_style='carto-positron',
                        mapbox_zoom=11,
                        title='Daegu Case Routes',
                        margin={
                            "r": 0,
                            "t": 25,
                            "l": 0,
                            "b": 0
                        },
                        showlegend=False)
route_fig.show()

# For performance reasons, the number of routes displayed were limited. The Daegu region was specifically selected because of the Shincheonji Church of Jesus incident.
コード例 #18
0
# open a zipped shapefile with the zip:// pseudo-protocol
geo_df = gpd.read_file("zip://ne_50m_rivers_lake_centerlines.zip")

lats = []
lons = []
names = []

for feature, name in zip(geo_df.geometry, geo_df.name):
    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))
        lats = np.append(lats, None)
        lons = np.append(lons, None)
        names = np.append(names, None)

fig = px.line_mapbox(lat=lats,
                     lon=lons,
                     hover_name=names,
                     mapbox_style="stamen-terrain",
                     zoom=1)
fig.show()
コード例 #19
0
def newGapGraph(whichPolygon,whichMap,whichGapPack):
    #gapwoo = gapsDict[whichPolygon][str(whichGapPack)]
    usegap = allGaps.loc[allGaps.POLYGON == whichPolygon,:]
    #usegapsmall = usegap[usegap['portion'].isin(gapwoo)]
    usegapsmall = usegap.loc[usegap['portion']== whichGapPack,:]

    #usepoly = allPoly.loc[allPoly.POLYGON == whichPolygon,:]
    #usepoly2 = usepoly.loc[usepoly.portion == 3,:]
    if whichMap == "sat":
        color_discrete_lks = color_discrete_map_st
    elif whichMap != 'sat':
        color_discrete_lks = color_discrete_map_st
    fig = px.line_mapbox(usegapsmall,
                lon = 'lon',
                lat = 'lat',
                zoom = 16,
                color = 'POLYGON',
                color_discrete_map=color_discrete_lks,
                width = 50,
                hover_data = {'portion'}
                )
    fig.update_layout(
             #autosize=True,
             width = 800,
             height = 800,
             showlegend = False,
                 
       
            )    
    fig.update_traces(line=dict(width=6))

        
    # for x in usegapsmall.portion.unique():   
    #     use = usegapsmall.loc[usegap.portion == x,]
    #     if x==usegapsmall.portion.unique().min():
    #         fig = px.line_mapbox(use,
    #             lon = 'lon',
    #             lat = 'lat',
    #             zoom = 14,
    #             color = 'POLYGON',
    #             color_discrete_map=color_discrete_lks,
    #             width = 50,
    #             hover_data = {'portion'}
    #             )
    #         fig.update_layout(
    #          #autosize=True,
    #          width = 800,
    #          height = 800,
    #          showlegend = False,
       
    #         )
            
    #     elif x != usegapsmall.portion.unique().min():
    #         fig.add_trace(
    #             px.line_mapbox(use,
    #                 lon = 'lon',
    #                 lat = 'lat',
    #                 zoom = 14,
    #                 color = 'POLYGON',
    #                 color_discrete_map=color_discrete_lks,
    #                 width = 50,
    #                 hover_data = {'portion'}

    #                 ).data[0],
    #             )    
    if whichMap == "sat":
       fig.update_layout(
           mapbox_style="satellite-streets",
           )

    return(fig)
コード例 #20
0
def get_figures(trips: Trips, charging: List[dict]):
    global consumption_fig, consumption_df, trips_map, consumption_fig_by_speed, table_fig, info, battery_info, \
        battery_table, consumption_graph_by_temp
    lats = []
    lons = []
    names = []
    for trip in trips:
        for points in trip.positions:
            lats = np.append(lats, points.latitude)
            lons = np.append(lons, points.longitude)
            names = np.append(names, [str(trip.start_at)])
        lats = np.append(lats, None)
        lons = np.append(lons, None)
        names = np.append(names, None)
    trips_map = px.line_mapbox(lat=lats,
                               lon=lons,
                               hover_name=names,
                               mapbox_style="stamen-terrain",
                               zoom=12)
    # table
    nb_format = Format(precision=2, scheme=Scheme.fixed, symbol=Symbol.yes)  # pylint: disable=no-member
    table_fig = dash_table.DataTable(
        id='trips-table',
        sort_action='native',
        sort_by=[{
            'column_id': 'id',
            'direction': 'desc'
        }],
        columns=[{
            'id': 'id',
            'name': '#',
            'type': 'numeric'
        }, {
            'id': 'start_at',
            'name': 'start at',
            'type': 'datetime'
        }, {
            'id':
            'duration',
            'name':
            'duration',
            'type':
            'numeric',
            'format':
            deepcopy(nb_format).symbol_suffix(" min").precision(0)
        }, {
            'id':
            'speed_average',
            'name':
            'average speed',
            'type':
            'numeric',
            'format':
            deepcopy(nb_format).symbol_suffix(" km/h").precision(0)
        }, {
            'id': 'consumption_km',
            'name': 'average consumption',
            'type': 'numeric',
            'format': deepcopy(nb_format).symbol_suffix(" kWh/100km")
        }, {
            'id': 'consumption_fuel_km',
            'name': 'average consumption fuel',
            'type': 'numeric',
            'format': deepcopy(nb_format).symbol_suffix(" L/100km")
        }, {
            'id': 'distance',
            'name': 'distance',
            'type': 'numeric',
            'format': nb_format.symbol_suffix(" km").precision(1)
        }, {
            'id': 'mileage',
            'name': 'mileage',
            'type': 'numeric',
            'format': nb_format
        }, {
            'id': 'altitude_diff',
            'name': 'Altitude diff',
            'type': 'numeric',
            'format': deepcopy(nb_format).symbol_suffix(" m").precision(0)
        }],
        style_data_conditional=[{
            'if': {
                'column_id': ['altitude_diff']
            },
            'color': 'dodgerblue',
            "text-decoration": "underline"
        }],
        data=trips.get_info(),
        page_size=50)
    # consumption_fig
    consumption_df = DataFrame.from_records(trips.get_long_trips())
    consumption_fig = px.histogram(consumption_df,
                                   x="date",
                                   y="consumption_km",
                                   title='Consumption of the car',
                                   histfunc="avg")
    consumption_fig.update_layout(yaxis_title="Consumption kWh/100Km")

    consumption_fig_by_speed = px.histogram(consumption_df,
                                            x="speed",
                                            y="consumption_km",
                                            histfunc="avg",
                                            title="Consumption by speed")
    consumption_fig_by_speed.update_traces(xbins_size=15)
    consumption_fig_by_speed.update_layout(bargap=0.05)
    consumption_fig_by_speed.add_trace(
        go.Scatter(mode="markers",
                   x=consumption_df["speed"],
                   y=consumption_df["consumption_km"],
                   name="Trips"))
    consumption_fig_by_speed.update_layout(xaxis_title="average Speed km/h",
                                           yaxis_title="Consumption kWh/100Km")
    kw_per_km = float(consumption_df["consumption_km"].mean())
    info = "Average consumption: {:.1f} kWh/100km".format(kw_per_km)

    # charging
    charging_data = DataFrame.from_records(charging)
    co2_per_kw = __calculate_co2_per_kw(charging_data)
    co2_per_km = co2_per_kw * kw_per_km / 100
    try:
        charge_speed = 3600 * charging_data["kw"].mean() / \
                       (charging_data["stop_at"] - charging_data["start_at"]).mean().total_seconds()
        price_kw = (charging_data["price"] / charging_data["kw"]).mean()
        total_elec = kw_per_km * trips.get_distance() / 100
    except (TypeError, KeyError,
            ZeroDivisionError):  # when there is no data yet:
        charge_speed = 0
        price_kw = 0
        total_elec = 0

    SUMMARY_CARDS["Average charge speed"]["text"] = f"{charge_speed:.2f} kW"
    SUMMARY_CARDS["Average emission"]["text"] = [
        html.P(f"{co2_per_km:.1f} g/km"),
        html.P(f"{co2_per_kw:.1f} g/kWh")
    ]
    SUMMARY_CARDS["Electricity consumption"]["text"] = [f"{total_elec:.0f} kWh", html.Br(), \
                                                        f"{total_elec * price_kw:.0f} {ElecPrice.currency}"]
    SUMMARY_CARDS["Average consumption"][
        "text"] = f"{consumption_df['consumption_km'].mean():.1f} kWh/100km"
    battery_table = dash_table.DataTable(
        id='battery-table',
        sort_action='native',
        sort_by=[{
            'column_id': 'start_at',
            'direction': 'desc'
        }],
        columns=[{
            'id': 'start_at',
            'name': 'start at',
            'type': 'datetime'
        }, {
            'id': 'stop_at',
            'name': 'stop at',
            'type': 'datetime'
        }, {
            'id': 'start_level',
            'name': 'start level',
            'type': 'numeric'
        }, {
            'id': 'end_level',
            'name': 'end level',
            'type': 'numeric'
        }, {
            'id':
            'co2',
            'name':
            'CO2',
            'type':
            'numeric',
            'format':
            deepcopy(nb_format).symbol_suffix(" g/kWh").precision(1)
        }, {
            'id':
            'kw',
            'name':
            'consumption',
            'type':
            'numeric',
            'format':
            deepcopy(nb_format).symbol_suffix(" kWh").precision(2)
        }, {
            'id':
            'price',
            'name':
            'price',
            'type':
            'numeric',
            'format':
            deepcopy(nb_format).symbol_suffix(" " +
                                              ElecPrice.currency).precision(2),
            'editable':
            True
        }],
        data=charging,
        style_data_conditional=[{
            'if': {
                'column_id': ['start_level', "end_level"]
            },
            'color': 'dodgerblue',
            "text-decoration": "underline"
        }, {
            'if': {
                'column_id': 'price'
            },
            'backgroundColor': 'rgb(230, 246, 254)'
        }],
    )
    consumption_by_temp_df = consumption_df[
        consumption_df["consumption_by_temp"].notnull()]
    if len(consumption_by_temp_df) > 0:
        consumption_fig_by_temp = px.histogram(
            consumption_by_temp_df,
            x="consumption_by_temp",
            y="consumption_km",
            histfunc="avg",
            title="Consumption by temperature")
        consumption_fig_by_temp.update_traces(xbins_size=2)
        consumption_fig_by_temp.update_layout(bargap=0.05)
        consumption_fig_by_temp.add_trace(
            go.Scatter(mode="markers",
                       x=consumption_by_temp_df["consumption_by_temp"],
                       y=consumption_by_temp_df["consumption_km"],
                       name="Trips"))
        consumption_fig_by_temp.update_layout(
            xaxis_title="average temperature in °C",
            yaxis_title="Consumption kWh/100Km")
        consumption_graph_by_temp = html.Div(
            Graph(figure=consumption_fig_by_temp),
            id="consumption_graph_by_temp")

    else:
        consumption_graph_by_temp = html.Div(Graph(style={'display': 'none'}),
                                             id="consumption_graph_by_temp")
    return True
コード例 #21
0
ファイル: appBetter.py プロジェクト: elimywilliams/Trussville
def newGapGraph(whichPolygon, whichMap, whichGapPack):
    totalGps = gsizeDict[whichPolygon]
    count = 0
    for i in range(0, totalGps + 1, 10):
        x = i
        count = count + 1

        if count == whichGapPack:
            print(x)
            gaps = (list(range(1, totalGps + 1, 1))[x:x + 10])
    #usedat = allLeaks.loc[allLeaks.POLYGON == whichPolygon,:]
    usegap = allGaps.loc[allGaps.POLYGON == whichPolygon, :]
    usegapsmall = usegap[usegap['portion'].isin(gaps)]
    usepoly = allPoly.loc[allPoly.POLYGON == whichPolygon, :]
    usepoly2 = usepoly.loc[usepoly.portion == 3, :]

    if whichMap == 'sat':
        color_discrete_map = {
            'P1': 'rgb(255,0,0)',
            'P2': 'rgb(255,0,0)',
            'P3': 'rgb(255,0,0)',
            'P4': 'rgb(255,0,0)'
        }
        color_discrete_lks = {
            'P1': 'rgb(255,255,255)',
            'P2': 'rgb(255,255,255)',
            'P3': 'rgb(255,255,255)',
            'P4': 'rgb(255,255,255)'
        }
    elif whichMap != 'sat':
        color_discrete_lks = {
            'P1': 'rgb(0, 0, 99)',
            'P2': 'rgb(0, 0, 99)',
            'P3': 'rgb(0, 0, 99)',
            'P4': 'rgb(0, 0, 99)'
        }
        color_discrete_map = {
            'P1': 'rgb(255,0,0)',
            'P2': 'rgb(255,0,0)',
            'P3': 'rgb(255,0,0)',
            'P4': 'rgb(255,0,0)'
        }

    fig = px.line_mapbox(usepoly2,
                         lon='lat',
                         lat='lon',
                         zoom=12,
                         color='POLYGON',
                         color_discrete_map=color_discrete_map)

    fig.update_layout(
        autosize=True,
        width=800,
        height=800,
        showlegend=False,
    )
    for x in range(usegapsmall.portion.min(), usegapsmall.portion.max() + 1):
        use = usegapsmall.loc[usegap.portion == x, ]
        fig.add_trace(
            px.line_mapbox(
                use,
                lon='lon',
                lat='lat',
                zoom=10,
                color='POLYGON',
                color_discrete_map=color_discrete_lks,
                width=10,
            ).data[0], )
    if whichMap == "sat":
        fig.update_layout(mapbox_style="satellite-streets", )
    return (fig)
# ## Visualizacion de de la Línea 12

# In[ ]:

# In[62]:

linea_12

# #### Todos los puntos de posición conectado por líneas

# In[63]:

fig = px.line_mapbox(linea_12,
                     lat="latitude",
                     lon="longitude",
                     color="id",
                     zoom=3,
                     height=300)

fig.update_layout(mapbox_style="carto-positron",
                  mapbox_zoom=11,
                  mapbox_center_lat=-34.6,
                  margin={
                      "r": 1,
                      "t": 0,
                      "l": 0,
                      "b": 0
                  })

fig.show()
コード例 #23
0
                  mapbox_zoom=3, mapbox_center = {"lat": 37.0902, "lon": -95.7129})
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()


# In[ ]:


import pandas as pd

us_cities = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv")
us_cities = us_cities.query("State in ['New York', 'Ohio']")

import plotly.express as px

fig = px.line_mapbox(us_cities, lat="lat", lon="lon", color="State", zoom=3, height=300)

fig.update_layout(mapbox_style="stamen-terrain", mapbox_zoom=4, mapbox_center_lat = 41,
    margin={"r":0,"t":0,"l":0,"b":0})

fig.show()


# In[ ]:


import plotly.graph_objects as go

fig = go.Figure(go.Scattermapbox(
    mode = "markers+lines",
    lon = [10, 20, 30],
コード例 #24
0
def newGapGraph(whichPolygon,whichMap,whichGapPack):
   #totalGps = gsizeDict[whichPolygon]
    gapwoo = gapsDict[whichPolygon][str(whichGapPack)]
    # count = 0    
    # for i in range(0,totalGps+1,10):
    #     x=i
    #     count = count + 1
       
    #     if count == whichGapPack:
    #         print(x)
    #         gaps= (list(range(1,totalGps+1,1))[x:x+10])
    # #usedat = allLeaks.loc[allLeaks.POLYGON == whichPolygon,:]    
    usegap = allGaps.loc[allGaps.POLYGON == whichPolygon,:]
    usegapsmall = usegap[usegap['portion'].isin(gapwoo)]
    usepoly = allPoly.loc[allPoly.POLYGON == whichPolygon,:]
    usepoly2 = usepoly.loc[usepoly.portion == 3,:]
    
    if whichMap == 'sat':
        color_discrete_map = {'P1': 'rgb(255,0,0)', 'P2': 'rgb(255,0,0)', 'P3': 'rgb(255,0,0)',
                              'P4': 'rgb(255,0,0)'}
        color_discrete_lks= {'P1': 'rgb(255,255,255)', 'P2': 'rgb(255,255,255)', 'P3': 'rgb(255,255,255)',
                              'P4': 'rgb(255,255,255)'}
    elif whichMap != 'sat':
        color_discrete_lks= {'P1': 'rgb(0, 0, 99)', 'P2': 'rgb(0, 0, 99)', 'P3': 'rgb(0, 0, 99)',
                              'P4': 'rgb(0, 0, 99)'}
        color_discrete_map = {'P1': 'rgb(255,0,0)', 'P2': 'rgb(255,0,0)', 'P3': 'rgb(255,0,0)',
                              'P4': 'rgb(255,0,0)'}
    
    # fig = px.line_mapbox(
    #     usepoly2,
    #     lon = 'lat',
    #     lat = 'lon',
    #     zoom = 12,
    #     color = 'POLYGON',
    #     color_discrete_map=color_discrete_map
    #         )
    #fig = go.Figure()
    

    #for x in range(usegapsmall.portion.min(),usegapsmall.portion.max()+1):
    for x in usegapsmall.portion.unique():   
        use = usegapsmall.loc[usegap.portion == x,]
        if x==usegapsmall.portion.unique().min():
            fig = px.line_mapbox(use,
                lon = 'lon',
                lat = 'lat',
                zoom = 14,
                color = 'POLYGON',
                color_discrete_map=color_discrete_lks,
                width = 50,
                hover_data = {'portion'}
                )
            fig.update_layout(
             #autosize=True,
             width = 800,
             height = 800,
             showlegend = False,
       
            )
            
        elif x != usegapsmall.portion.unique().min():
            fig.add_trace(
                px.line_mapbox(use,
                    lon = 'lon',
                    lat = 'lat',
                    zoom = 14,
                    color = 'POLYGON',
                    color_discrete_map=color_discrete_lks,
                    width = 50,
                    hover_data = {'portion'}

                    ).data[0],
                )    
    if whichMap == "sat":
       fig.update_layout(
           mapbox_style="satellite-streets",
           )

    return(fig)
コード例 #25
0
ファイル: app.py プロジェクト: klane/dse-capstone
def plot_roads(plotcat, snap_var, timestamp_value, horizon):
    # plotly.io.templates.default='plotly'
    #del fig

    if plotcat.find("speed") >= 0:
        catord = {
            plotcat: ["fast", "moderate", "slow", "very slow", "no data"]
        }
    else:
        catord = {
            plotcat: [
                'overpredict > 5 mph', 'overpredict 1 - 5 mph', 'within 1 mph',
                'underpredict 1 - 5 mph', 'underpredict > 5 mph'
            ]
        }

    snap_var = pd.read_json(snap_var, orient='split')

    selhr, sensors_spr = find_selhr(snap_var)

    selhrg = road_group_split(selhr, splitcat=plotcat)
    #keep_cols=keepcols)

    fig = px.line_mapbox(
        #fig=px.scatter_mapbox
        selhrg,
        lat="latitude",
        lon="longitude",
        color=plotcat,
        mapbox_style="carto-darkmatter",
        #mapbox_style="carto-positron",
        #color_continuous_scale="aggrnyl" ,
        line_group="linegroup",
        hover_data=list(selhrg.columns),
        center={
            "lat": 37.34,
            "lon": -121.93
        },
        color_discrete_map=cdme if plotcat == "err_cat" else cdm,
        zoom=10,
        category_orders=catord
        # height=600, width=600
    )

    for dat in fig.data:
        dat["line"]["width"] = 5

    sensors_spr["size"] = 3
    fig2 = px.scatter_mapbox(
        sensors_spr.reset_index(),
        lat="latitude",
        lon="longitude",
        #hover_data=["stype","fwy","direc","abs_pm","pred_speed"],
        hover_name="sid",
        hover_data=list(sensors_data.reset_index().columns),
        mapbox_style="stamen-terrain",
        color="stype",
        color_discrete_map={"ML": "blue"},
        size="size",
        opacity=0.35,
        size_max=5)
    #for dat in fig2.data:
    fig.add_trace(fig2.data[0])

    fig.update_layout(
        title="<b>PEMS Sensor Map Snapshot for {} with {}pts Horizon</b>".
        format(timestamp_value, horizon),
        uirevision=True,
        height=600,
        # width=1200,
        autosize=True,
        template="plotly_dark",
        plot_bgcolor='rgba(0, 0, 0, 0)',
        paper_bgcolor='rgba(0, 0, 0, 0)',
        font=dict(size=14, color='white'),
        margin={
            "r": 40,
            "t": 50,
            "l": 10,
            "b": 10
        })

    return fig
コード例 #26
0
preds['Latitude'] = preds[preds.columns[1]]
preds['Longitude'] = preds[preds.columns[2]]
preds.drop([preds.columns[0], preds.columns[1], preds.columns[2]],
           axis=1,
           inplace=True)
preds['Prediction'] = 1

preoutputDf = yhat.append(preds, ignore_index=True)

origin = pd.DataFrame(data={
    'Latitude': preoutputDf.iloc[0]['Latitude'],
    'Longitude': preoutputDf.iloc[0]['Longitude'],
    'Prediction': 1
},
                      columns=['Latitude', 'Longitude', 'Prediction'],
                      index=[len(yhat.index)])

outputDf = (yhat.append(origin, ignore_index=True)).append(preds,
                                                           ignore_index=True)
outputDf['Prediction'] = outputDf['Prediction'].fillna(0)

fig = px.line_mapbox(outputDf,
                     lat='Latitude',
                     lon='Longitude',
                     color='Prediction',
                     center=dict(lat=0, lon=180),
                     zoom=0,
                     mapbox_style="stamen-terrain")
fig.show()
コード例 #27
0
ファイル: plotly-express.py プロジェクト: zhywf/plotly.py
    carshare,
    lat="centroid_lat",
    lon="centroid_lon",
    color="peak_hour",
    size="car_hours",
    color_continuous_scale=px.colors.cyclical.IceFire,
    size_max=15,
    zoom=10,
)
fig.write_html(os.path.join(dir_name, "scatter_mapbox.html"))

import plotly.express as px

carshare = px.data.carshare()
fig = px.line_mapbox(carshare,
                     lat="centroid_lat",
                     lon="centroid_lon",
                     color="peak_hour")
fig.write_html(os.path.join(dir_name, "line_mapbox.html"))

import plotly.express as px

sample_geojson = {
    "type":
    "FeatureCollection",
    "features": [{
        "type": "Feature",
        "id": "the_polygon",
        "geometry": {
            "type":
            "Polygon",
            "coordinates": [[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0],
コード例 #28
0
def newGapGraph(whichPolygon, whichMap, whichGapPack):
    usegap = allGaps.loc[allGaps.POLYGON == whichPolygon, :]
    usegapsmall = usegap.loc[usegap['portion'] == whichGapPack, :]

    if usegapsmall.loc[:, 'multiple'].reset_index(drop=True)[0] == True:
        firstgapsmall = usegapsmall.loc[usegapsmall.subportion == 1, ]
        secgapsmall = usegapsmall.loc[usegapsmall.subportion == 2, ]

        if whichMap == "sat":
            color_discrete_lks = color_discrete_map_st
        elif whichMap != 'sat':
            color_discrete_lks = color_discrete_map_st
        fig = px.line_mapbox(firstgapsmall,
                             lon='lon',
                             lat='lat',
                             zoom=16,
                             color='POLYGON',
                             color_discrete_map=color_discrete_lks,
                             width=50,
                             hover_data={'portion'})
        fig.update_layout(
            width=800,
            height=800,
            showlegend=False,
        )
        fig.add_trace(
            px.line_mapbox(secgapsmall,
                           lon='lon',
                           lat='lat',
                           zoom=14,
                           color='POLYGON',
                           color_discrete_map=color_discrete_lks,
                           width=50,
                           hover_data={'portion'}).data[0], )
        fig.update_traces(line=dict(width=6))

    elif usegapsmall.loc[:, 'multiple'].reset_index(drop=True)[0] == False:
        if whichMap == "sat":
            color_discrete_lks = color_discrete_map_st
        elif whichMap != 'sat':
            color_discrete_lks = color_discrete_map_st
        fig = px.line_mapbox(usegapsmall,
                             lon='lon',
                             lat='lat',
                             zoom=16,
                             color='POLYGON',
                             color_discrete_map=color_discrete_lks,
                             width=50,
                             hover_data={'portion'})
        fig.update_layout(
            #autosize=True,
            width=800,
            height=800,
            showlegend=False,
        )

        fig.update_traces(line=dict(width=6))

    # for x in usegapsmall.portion.unique():
    #     use = usegapsmall.loc[usegap.portion == x,]
    #     if x==usegapsmall.portion.unique().min():
    #         fig = px.line_mapbox(use,
    #             lon = 'lon',
    #             lat = 'lat',
    #             zoom = 14,
    #             color = 'POLYGON',
    #             color_discrete_map=color_discrete_lks,
    #             width = 50,
    #             hover_data = {'portion'}
    #             )
    #         fig.update_layout(
    #          #autosize=True,
    #          width = 800,
    #          height = 800,
    #          showlegend = False,

    #         )

    #     elif x != usegapsmall.portion.unique().min():
    #         fig.add_trace(
    #             px.line_mapbox(use,
    #                 lon = 'lon',
    #                 lat = 'lat',
    #                 zoom = 14,
    #                 color = 'POLYGON',
    #                 color_discrete_map=color_discrete_lks,
    #                 width = 50,
    #                 hover_data = {'portion'}

    #                 ).data[0],
    #             )
    if whichMap == "sat":
        fig.update_layout(mapbox_style="satellite-streets", )

    return (fig)
コード例 #29
0
def update_gapLeak(whichPolygon, whichMap):
    usedat = allLeaks.loc[allLeaks.POLYGON == whichPolygon, :]
    usepoly = allPoly.loc[allPoly.POLYGON == whichPolygon, :]
    usegap = allGaps.loc[allGaps.POLYGON == whichPolygon, :]
    usepoly2 = usepoly.loc[usepoly.portion == 3, :]
    #howmany = usegap.portion.drop_duplicates().size
    if whichPolygon == 'P1':
        #howmany =129
        howmany = 50
    elif whichPolygon == "P2":
        #howmany = 72
        howmany = 50
    elif whichPolygon == "P3":
        #howmany = 141
        howmany = 50
    elif whichPolygon == 'P4':
        howmany = 31

    if whichMap == 'sat':
        color_discrete_map = {
            'P1': 'rgb(255,0,0)',
            'P2': 'rgb(255,0,0)',
            'P3': 'rgb(255,0,0)',
            'P4': 'rgb(255,0,0)'
        }
        color_discrete_lks = {
            'P1': 'rgb(255,255,255)',
            'P2': 'rgb(255,255,255)',
            'P3': 'rgb(255,255,255)',
            'P4': 'rgb(255,255,255)'
        }
    elif whichMap != 'sat':
        color_discrete_lks = {
            'P1': 'rgb(0, 0, 99)',
            'P2': 'rgb(0, 0, 99)',
            'P3': 'rgb(0, 0, 99)',
            'P4': 'rgb(0, 0, 99)'
        }
        color_discrete_map = {
            'P1': 'rgb(255,0,0)',
            'P2': 'rgb(255,0,0)',
            'P3': 'rgb(255,0,0)',
            'P4': 'rgb(255,0,0)'
        }

    fig = px.line_mapbox(usepoly2,
                         lon='lat',
                         lat='lon',
                         zoom=12,
                         color='POLYGON',
                         color_discrete_map=color_discrete_map)

    fig.update_layout(
        autosize=True,
        width=800,
        height=800,
        showlegend=False,
    )
    for x in range(howmany):
        #for x in range(32):
        i = x + 1
        use = usegap.loc[usegap.portion == i, ]
        fig.add_trace(
            px.line_mapbox(
                use,
                lon='lon',
                lat='lat',
                zoom=10,
                color='POLYGON',
                color_discrete_map=color_discrete_lks,
                width=10,
            ).data[0], )
    if whichMap == "sat":
        fig.update_layout(mapbox_style="satellite-streets", )
    return fig
コード例 #30
0
if int(inputf[12]) == 0:
    ax, bx = bx, ax
os.remove(dirct + '/outdata.txt')  #удаление временных файлов
os.remove(dirct + '/Statistic.txt')  #удаление временных файлов
#######################################################################################

fig = px.scatter_mapbox(data, lat="Lat", lon="Lon", zoom=13,
                        color="Density")  #Создание карты с данными о жителях

################################################################## Создание эллипса
x, y = ellipse(float(ae), float(be))
for i in range(len(x)):
    x[i], y[i] = RotateCoord(x[i], y[i], float(angle), float(Mx), float(My))
    x[i], y[i] = PosToGeo(float(x[i]), float(y[i]), zone,
                          L0)  # Перевод координат
fig2 = px.line_mapbox(lat=x, lon=y)
##################################################################

################################################################# Добавление оптимальной точки
Mx, My = PosToGeo(float(Mx), float(My), zone, L0)
markerx = [Mx]
markery = [My]
markername = ["Optimal point"]
fig3 = px.scatter_mapbox(lon=markery,
                         lat=markerx,
                         size=markery,
                         hover_name=markername)
##########################################################

################################################################## Вывод параметров в тхт файл
file.write('Optimal point: Lat: ' + str(Mx) + '; Lon:' + str(My) + '\n')