コード例 #1
0
def plot_2D(df, basemap=False, figsize=(10, 10), save=False, fname='2D'):
    # specify line and direction query
    linename = df['PublishedLineName'].unique()[0]
    direction = df['DirectionRef'].unique()[0]

    # read route shapefile
    gdf = gpd.read_file("MTA_shp/bus_routes_nyc_aug2017.shp")
    gdf.to_crs(epsg=4326, inplace=True)

    # plot route
    route_shp = gdf[gdf['route_dir'] == '%s_%s' % (linename, direction)]
    route_shp.plot(color='red', figsize=figsize)

    # save figure locally if specified
    if save:
        plt.savefig("%s.png" % (fname), dpi=300)
    else:
        pass

    # plot on a basemap or not
    # requires "mplleaflet" package
    if basemap:
        mlf.display()
    else:
        plt.show()
コード例 #2
0
def draw_road_graph(graph, draw_edges=True, draw_nodes=True):
    """
    Plots nodes and edges of a road graph, overlays the graph over the world map.

    :param graph: the road graph that shall be plotted
    :type graph: RoadGraphX
    :param draw_edges: should plot edges
    :param draw_nodes: should plot nodes
    :return:
    """
    pos = {}
    for node in graph.graph.nodes():
        pos[node] = [float(i) for i in node]

    colors = []
    for start, finish, edge_data in graph.graph.edges(data=True):
        colors.append(edge_data['fun_factor'])
    if draw_nodes:
        nx.draw_networkx_nodes(graph.graph, pos=pos, node_size=10)
    if draw_edges:
        nx.draw_networkx_edges(graph.graph,
                               pos=pos,
                               edge_color=colors,
                               width=5)

    return mplleaflet.display()
コード例 #3
0
def leaflet_plot_stations(binsize, hashid):
    df = pd.read_csv('data/C2A2_data/BinSize_d{}.csv'.format(binsize))
    station_locations_by_hash = df[df['hash'] == hashid]
    lons = station_locations_by_hash['LONGITUDE'].tolist()
    lats = station_locations_by_hash['LATITUDE'].tolist()
    plt.figure(figsize=(8, 8))
    plt.scatter(lons, lats, c='r', alpha=0.7, s=200)
    return mplleaflet.display()
def plot_stations(longitudes, latitudes, embedded = False):
    if embedded:
        plt.figure(figsize = (8, 8))
    plt.scatter(longitudes, latitudes, 
                c = 'b',
                marker = 'D',
                alpha = 0.7, 
                s = 200)
    return mplleaflet.display() if embedded else mplleaflet.show()
コード例 #5
0
ファイル: data_clean.py プロジェクト: clapham13/Urban_Sensing
def plot_gpx(df):
    '''
    Takes in a gpx dataframe and plots on mplleaflet background
    '''
    fig, ax = plt.subplots(figsize=(5, 5))
    df = df.dropna()
    ax.plot(df['Longitude'],
            df['Latitude'],
            color='darkorange',
            linewidth=5,
            alpha=0.5)
    sub = 10
    return mplleaflet.display(fig=fig, tiles='esri_aerial')
def leaflet_plot_stations(binsize, hashid):

    df = pd.read_csv('data/C2A2_data/BinSize_d{}.csv'.format(binsize))

    station_locations_by_hash = df[df['hash'] == hashid]

    lons = station_locations_by_hash['LONGITUDE'].tolist()
    lats = station_locations_by_hash['LATITUDE'].tolist()

    plt.figure(figsize=(8,8))

    plt.scatter(lons, lats, c='r', alpha=0.7, s=200)

    return mplleaflet.display()
コード例 #7
0
def test_plot_leaflet(location= ''):
    lon = -84.0156
    lat = 41.9164
    plt.figure(figsize= (10, 10))
    # print(ml.data['latitude'][:10])
    # print(ml.data['longitude'][:10])
    plt.scatter(ml.data['longitude'][:600], ml.data['latitude'][:600], c= 'r', alpha= 0.7, s =1)
    # plt.hist2d(ml.data['longitude'][:100], ml.data['latitude'][:100], 
                # bins= 50)
    # plt.scatter(lon, lat, c= 'r', alpha= 0.7, s =5)
    # img_to_save = os.path.join(os.getcwd(), 'static', 'test1.png')
    # fig.savefig(img_to_save, format= 'png')
    # encoded = base64.b64encode(tmpfile.getvalue())
    return mplleaflet.display()
コード例 #8
0
    def map(self,
            map_type='osm',
            embed=False,
            ax=None,
            size=(10, 10),
            plot='plot',
            **kwargs):
        """Plot trajectory on map.

        Parameters
        ----------
        - map_type can be e.g. osm, esri_aerial, esri_worldtopo, etc. see:
        https://github.com/jwass/mplleaflet/blob/master/mplleaflet/maptiles.py

        - embed: if True, embed plot in Jupyter. If False (default), open in
        browser.

        - ax: if not None, use provided matplotlib axes.

        - size: when embedded, size of the figure.

        - plot: 'plot' or 'scatter'

        - **kwargs: any plt.plot or plt.scatter keyword arguments
        """
        if ax is None:
            fig, ax = plt.subplots(figsize=size)
        else:
            fig = ax.figure

        if plot == 'plot':
            ax.plot(self.longitude, self.latitude, '.-r', **kwargs)
        elif plot == 'scatter':
            ax.scatter(self.longitude, self.latitude, **kwargs)
        else:
            raise ValueError(f'Unrecognized plot type: {plot}')

        parameters = {'fig': fig, 'tiles': map_type}
        if embed:
            leaflet = mplleaflet.display(**parameters)
        else:
            leaflet = mplleaflet.show(**parameters)

        return leaflet
コード例 #9
0
def leaflet_plot_stations(binsize, hashid):

    df = pd.read_csv('data/C2A2_data/BinSize_d{}.csv'.format(binsize))
    #print (df.head())
    #Index(['ID', 'LATITUDE', 'LONGITUDE', 'ELEVATION', 'STATE', 'NAME', 'GSNFLAG',
      # 'HCNFLAG', 'WMOID', 'x', 'y', 'x_group', 'y_group', 'xy_group', 'hash'],
     # dtype='object')


    station_locations_by_hash = df[df['hash'] == hashid]

    lons = station_locations_by_hash['LONGITUDE'].tolist()
    lats = station_locations_by_hash['LATITUDE'].tolist()

    plt.figure(figsize=(8,8))

    plt.scatter(lons, lats, c='r', alpha=0.7, s=200)

    return mplleaflet.display()
コード例 #10
0
ファイル: community.py プロジェクト: yanchick/vk_miner
    def plot_geodata(self, embed=False):
        """Plot users on the map.

        Args:
            embed: True if map should be drawn in IPython Notebook cell.
        """
        counter = Counter(u.city_id for u in self.get_users())
        data = []
        for city_id, count in counter.items():
            if np.isnan(city_id):
                continue
            name, lat, lon = self._cities[city_id]
            if (lat, lon) != (None, None):
                data.append((lon, lat, count * 3))
        xs, ys, sizes = list(zip(*data))
        plt.scatter(xs, ys, s=sizes)
        if embed:
            return mplleaflet.display()
        else:
            return mplleaflet.show()
コード例 #11
0
def choropleth(df, grid_size,
               bounds=None, 
               latitude="latitude", 
               longitude="longitude", 
               tiles='cartodb_positron', 
               vmax=10, 
               cmap="viridis", 
               column="latitude", 
               crs=None,
               figsize=None):
    if figsize is None:
        figsize = [10,10] 
    fig = plt.figure(figsize=figsize)
    
    grid = create_grid(df, grid_size, bounds, latitude, longitude, column, crs, vmax)
    
    if len(grid) > 0:
        for idx, r in grid.iterrows():
            color = plt.get_cmap(cmap).colors[int(r.color) if not np.isnan(r.color) else 0]
            plt.gca().add_patch(PolygonPatch(r.geometry, alpha=0.5,color=color, zorder=2))
    return mplleaflet.display(fig, tiles=tiles)
コード例 #12
0
ファイル: utilities.py プロジェクト: pdyban/motofun
def draw_road_graph(graph, draw_edges=True, draw_nodes=True):
    """
    Plots nodes and edges of a road graph, overlays the graph over the world map.

    :param graph: the road graph that shall be plotted
    :type graph: RoadGraphX
    :param draw_edges: should plot edges
    :param draw_nodes: should plot nodes
    :return:
    """
    pos = {}
    for node in graph.graph.nodes():
        pos[node] = [float(i) for i in node]

    colors = []
    for start, finish, edge_data in graph.graph.edges(data=True):
        colors.append(edge_data['fun_factor'])
    if draw_nodes:
        nx.draw_networkx_nodes(graph.graph, pos=pos, node_size=10)
    if draw_edges:
        nx.draw_networkx_edges(graph.graph, pos=pos, edge_color=colors, width=5)

    return mplleaflet.display()
コード例 #13
0
ファイル: tri_tide_movie.py プロジェクト: urbanows/notebook
V = (f * vamp *
     np.cos(v + thours[k] * omega + u - vpha * np.pi / 180)).sum(axis=1)

w = units['knots'] * (U + 1j * V)

wf = np.NaN * np.ones_like(lonf, dtype=w.dtype)
wf[inbox] = w

# FIXME: Cannot use masked arrays and tricontour!
# wf = ma.masked_invalid(wf)
# cs = ax.tricontour(lonf, latf, trif, np.abs(wf).filled(fill_value=0))
# fig.colorbar(cs)
q = plt.quiver(lon, lat, U, V, scale=vscale, color='white')
plt.axis(bbox)  # Vineyard sound 2.
#q.set_title('{}'.format(glocals[k]))
mplleaflet.display(fig=fig, tiles='esri_aerial')

# In[ ]:

js = mplleaflet.fig_to_geojson(fig=fig)
with open("test.json", "w") as outfile:
    json.dump(js, outfile, indent=4)

# In[ ]:

get_ipython().magic(u'matplotlib inline')

import matplotlib.pyplot as plt
from JSAnimation import IPython_display
from matplotlib.animation import FuncAnimation
コード例 #14
0
                   [0.76, 0.15, 0.05, 0.38]])
# weight = np.around(np.random.uniform(low=0.01, high=0.99, size=(5, 4)), decimals=2)

R = 1
Alpha = 0.1
c = 0.1
Et = 18
E0 = 1
model = som.train_SOM(weight, dataset.values, Alpha, c, R, Et, E0)
klaster = som.test_SOM(model, dataset.values)
klaster = np.ravel(klaster)
sil = silhouette_score(dataset.values, klaster, metric='euclidean')
print(sil)

dataset['klaster'] = klaster
fig, ax = plt.subplots(figsize=(17, 10))
print(set(dataset['klaster'].values))
plot = ax.scatter(data['longitude'],
                  data['latitude'],
                  s=dataset['confidence'] * 100,
                  Alpha=0.5,
                  c=dataset['klaster'],
                  cmap='jet')

plt.colorbar(plot)
plt.show()
mplleaflet.display(fig=fig)

# unique, counts = np.unique(klaster, return_counts=True)
# print(dict(zip(unique, counts)))
# print(dataset.groupby(['klaster']).mean())
コード例 #15
0
ファイル: fvcom_test.py プロジェクト: rsignell-usgs/mwra-wq
lonc = cube.mesh.face_coordinates[:,0]
latc = cube.mesh.face_coordinates[:,1]


# In[16]:

subsample = 5
# find velocity points in bounding box
ind = np.argwhere((lonc >= bbox[0]) & (lonc <= bbox[1]) & (latc >= bbox[2]) & (latc <= bbox[3]))
np.random.shuffle(ind)
Nvec = int(len(ind) / subsample)
idv = ind[:Nvec]


# In[17]:

import mplleaflet
fig = plt.figure(figsize=(10,5))
vscale = 30  # smaller makes arrows bigger
q = plt.quiver(lonc[idv], latc[idv], u[idv], v[idv], scale=vscale, color='white')
plt.axis(bbox) 
#q.set_title('{}'.format(glocals[k]))
mplleaflet.display(fig=fig, tiles='esri_aerial')


# In[ ]:



コード例 #16
0
ファイル: EDA.py プロジェクト: max030/AIRBNB_ADS_Project
plt.title("roomtype")
plt.xlabel("id")
plt.ylabel("count")
sns.plt.show()

# In[ ]:

# In[42]:

proprytypeDF = edadata.groupby('property_type').id.count()
proprytypeDF.hist()

# In[47]:

roomPrptyDF = edadata.groupby(['property_type', 'room_type']).price.mean()
roomPrptyDF.hist()

# In[10]:

from pandas.tools.plotting import scatter_matrix
scatter_matrix(edadata, alpha=0.2, figsize=(10, 10), diagonal='kde')

# In[ ]:

import mplleaflet

sample = edadata.sample(1000)
plt.scatter(sample['longitude'], sample['latitude'])

mplleaflet.display()
コード例 #17
0
    overlay = nx.read_gml(overlay_path).to_undirected()

    mapping = {}
    for ii, node in enumerate(underlay.nodes()):
        mapping[str(ii)] = node

    overlay = nx.relabel_nodes(overlay, mapping).to_undirected()

    fig, ax = plt.subplots()

    nx.draw_networkx_nodes(overlay,
                           pos=pos_dict,
                           node_size=10,
                           node_color='red',
                           edge_color='k',
                           alpha=.5,
                           with_labels=True)
    nx.draw_networkx_edges(overlay,
                           pos=pos_dict,
                           edge_color='blue',
                           alpha=1,
                           width=5.0)
    nx.draw_networkx_labels(overlay, pos=pos_dict, label_pos=10.3)

    mplleaflet.display(fig=ax.figure)
    mplleaflet.save_html(fig=ax.figure,
                         fileobj=os.path.join(
                             "results", args.underlay,
                             "{}.html".format(args.architecture)))
コード例 #18
0
ファイル: wq_test.py プロジェクト: rsignell-usgs/mwra-wq
# In[12]:

plt.figure(figsize=(16,6))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_extent(bbox)
ax.coastlines(resolution='10m')
plt.tricontourf(triang, zcube.data, levels=levs)
plt.colorbar(fraction=0.046, pad=0.04)
plt.tricontour(triang, zcube.data, colors='k',levels=levs)
tstr = tvar.units.num2date(tvar.points[itime])
gl = ax.gridlines(draw_labels=True)
gl.xlabels_top = False
gl.ylabels_right = False
plt.title('%s: %s: %s' % (var,tstr,zcube.attributes['title']));


# In[13]:

import mplleaflet
fig = plt.figure(figsize=(6,8))
plt.tricontourf(triang, zcube.data, levels=levs)
plt.axis(bbox)  # Vineyard sound 2.
mplleaflet.display()


# In[ ]:



    m = folium.Map(location=[53.235048, -1.421629], zoom_start=13)
    for i in range(0, df_links.shape[0]):
        link = df_links.iloc[i]
        lons = link['the_geom'].coords.xy[0]  #coordinates in latlon
        lats = link['the_geom'].coords.xy[1]
        #gid = int(link.gid)
        xs = []
        ys = []
        n_segments = len(lons)
        for j in range(0, n_segments):
            (x, y) = pyproj.transform(
                wgs84, bng, lons[j], lats[j]
            )  #project to BNG -- uses nonISO lonlat convention  #TODO faster to cache this!
            xs.append(x)
            ys.append(y)
        color = 'r'
        folium.PolyLine(locations=[ys, xs]).add_to(m)
    m.save("chesterfield5.html")


plotSelectedODRoutes(con, cur)
mplleaflet.display(fig=ax.figure, crs=df.crs, tiles="cartodb_positron")
# Playing with folium
import folium
map_osm = folium.Map(location=[53.235048, -1.421629],
                     zoom_start=13,
                     tiles="cartodbpositron")
map_osm.save("chesterfield.html")
map_osm1 = folium.Map(location=[53.235048, -1.421629], zoom_start=13)
map_osm1.save("chesterfield1.html")