using pycharts plot coordinates on map - python

I use coordinates from csv file to plot on the map. But just only one point on the map.
from pyecharts import Geo
import pandas as pd
df=pd.read_csv(r"C:\157.csv")
df.head()
geo_cities_coords={i:[df.iloc[i]["Lon"],df.iloc[i]["Lat"]] for i in range(len(df))}
print(geo_cities_coords)
attr=list(df["City"])
value=list(df["Days"]/100000)
geo = Geo("Title", "subtitle", title_color="#fff", title_pos="center",width=1200, height=600, background_color='#404a59')
geo.add("",attr,value,visual_range=[0,100],symbol_size= 5,
visual_text_color= "#fff",is_piecewise = True,
is_visualmap= True,maptype = '北京', visual_split_number= 10,
geo_cities_coords=geo_cities_coords)
geo.render( 'test.html')
CSV file format:
City,Lat,Lon,Days
1,39.97556667,116.33035,39201.35731
2,39.97545,116.3302333,39201.35903
3,39.97383333,116.3329667,39201.52389

Related

Reverse Array in a dataframe

Hi I am trying to extract data from a netCDF file, but the data is upside down. How can I reverse the database:
The data I want to extract is the height data from the (netcdf) at the points I have in the CSV file. my Data:
import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import pandas as pd
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Path, PathPatch
csv_data = np.loadtxt('CSV with target coordinates',skiprows=1,delimiter=',')
num_el = csv_data[:,0]
lat = csv_data[:,1]
lon = csv_data[:,2]
value = csv_data[:,3]
data = Dataset("elevation Data",'r')
lon_range = data.variables['x_range'][:]
lat_range = data.variables['y_range'][:]
topo_range = data.variables['z_range'][:]
spacing = data.variables['spacing'][:]
dimension = data.variables['dimension'][:]
z = data.variables['z'][:]
lon_num = dimension[0]
lat_num = dimension[1]
etopo_lon = np.linspace(lon_range[0],lon_range[1],dimension[0])
etopo_lat = np.linspace(lat_range[0],lat_range[1],dimension[1])
topo = np.reshape(z, (lat_num, lon_num))
height = np.empty_like(num_el)
desired_lat_idx = np.empty_like(num_el)
desired_lon_idx = np.empty_like(num_el)
for i in range(len(num_el)):
tmp_lat = np.abs(etopo_lat - lat[i]).argmin()
tmp_lon = np.abs(etopo_lon - lon[i]).argmin()
desired_lat_idx[i] = tmp_lat
desired_lon_idx[i] = tmp_lon
height[i] = topo[tmp_lat,tmp_lon]
height[height<-10]=0
print(len(desired_lat_idx))
print(len(desired_lon_idx))
print(len(height))
dfl= pd.DataFrame({
'Latitude' : lat.reshape(-1),
'Longitude': lon.reshape(-1),
'Altitude': height.reshape(-1)
});
print(dfl)
# but the Lat should not be changed here (the dfl must be correct)
df =dfl
lat=np.array(df['Latitude'])
lon=np.array(df['Longitude'])
val=np.array(df['Altitude'])
m = basemap.Basemap(projection='robin', lon_0=0, lat_0=0, resolution='l',area_thresh=1000)
m.drawcoastlines(color = 'black')
x,y = m(lon,lat)
colormesh= m.contourf(x,y,val,100, tri=True, cmap = 'terrain')
plt.colorbar(location='bottom',pad=0.04,fraction=0.06)
plt.show()
I have already tried:
lat = csv_data[:,1]
lat= lat*(-1)
But this didn´t work
It's a plotting artifact().
Just do:
colormesh= m.contourf(x,y[::-1],val,100, tri=True, cmap = 'terrain')
y[::-1] will reverse the order of the y latitude elements (as opposed to the land-mass outlines; and while keeping the x longitude coordinates the same) and hence flip them.
I've often had this problem with plotting numpy image data in the past.
Your raw CSV data are unlikely to be flipped themselves (why would they be?). You should try sanity-checking them [I am not a domain expert I'm afraid]! Overlaying an actual coordinate grid can help with this.
Another way to do it is given here: Reverse Y-Axis in PyPlot
You could also therefore just do
ax = plt.gca()
ax.invert_yaxis()

Folium popup does not appear python

I have a geodataframe with Multistring Geometry. I wanted to plot an interactive map, on which when I click on each line, the name and id would appear! I can see that mouse form would change but nothing will appear. I also tried to define the names as labels but it did not work!
Ex_centreLine_map= folium.Map(location = [43.7180, -79.3762], zoom_start=12)
folium.Choropleth(
centreline_gdf[centreline_gdf.geometry.length> 0.00001],
line_weight=3,
line_color='blue',
popup=centreline_gdf[['lf_name', 'lfn_id']]).add_to(Ex_centreLine_map)
Ex_centreLine_map
you have not provided any sample data, so I have used some road data to make a MWE
you can do native folium however it's simpler to use geopandas explore()
for native folium you can to use folium.GeoJson()
import geopandas as gpd
import pandas as pd
import shapely.wkt
import io
df = pd.read_csv(io.StringIO("""ref;lanes;highway;maxspeed;length;name;geometry
A3015;2;primary;40 mph;40.68;Rydon Lane;MULTILINESTRING ((-3.4851169 50.70864409999999, -3.4849879 50.7090007), (-3.4857269 50.70693379999999, -3.4853034 50.7081574), (-3.488620899999999 50.70365289999999, -3.4857269 50.70693379999999), (-3.4853034 50.7081574, -3.4851434 50.70856839999999), (-3.4851434 50.70856839999999, -3.4851169 50.70864409999999))
A379;3;primary;50 mph;177.963;Rydon Lane;MULTILINESTRING ((-3.4763853 50.70886769999999, -3.4786112 50.70811229999999), (-3.4746017 50.70944449999999, -3.4763853 50.70886769999999), (-3.470350900000001 50.71041779999999, -3.471219399999999 50.71028909999998), (-3.465049699999999 50.712158, -3.470350900000001 50.71041779999999), (-3.481215600000001 50.70762499999999, -3.4813909 50.70760109999999), (-3.4934747 50.70059599999998, -3.4930204 50.7007898), (-3.4930204 50.7007898, -3.4930048 50.7008015), (-3.4930048 50.7008015, -3.4919513 50.70168349999999), (-3.4919513 50.70168349999999, -3.49137 50.70213669999998), (-3.49137 50.70213669999998, -3.4911565 50.7023015), (-3.4911565 50.7023015, -3.4909108 50.70246919999999), (-3.4909108 50.70246919999999, -3.4902349 50.70291189999999), (-3.4902349 50.70291189999999, -3.4897693 50.70314579999999), (-3.4805021 50.7077218, -3.4806265 50.70770150000001), (-3.488620899999999 50.70365289999999, -3.4888806 50.70353719999999), (-3.4897693 50.70314579999999, -3.489176800000001 50.70340539999999), (-3.489176800000001 50.70340539999999, -3.4888806 50.70353719999999), (-3.4865751 50.70487679999999, -3.4882604 50.70375799999999), (-3.479841700000001 50.70784459999999, -3.4805021 50.7077218), (-3.4882604 50.70375799999999, -3.488620899999999 50.70365289999999), (-3.4806265 50.70770150000001, -3.481215600000001 50.70762499999999), (-3.4717096 50.71021009999998, -3.4746017 50.70944449999999), (-3.4786112 50.70811229999999, -3.479841700000001 50.70784459999999), (-3.471219399999999 50.71028909999998, -3.4717096 50.71021009999998))"""),
sep=";")
gdf = gpd.GeoDataFrame(df, geometry=df["geometry"].apply(shapely.wkt.loads), crs="epsg:4326")
gdf.explore(style_kwds={"weight":10})
native folium
import folium
m = folium.Map(
location=[sum(gdf.total_bounds[[1, 3]]) / 2, sum(gdf.total_bounds[[0, 2]]) / 2],
zoom_start=12,
)
def style_fn(x):
return {"color":"blue", "weight":3}
folium.GeoJson(
gdf,
style_function=style_fn,
popup=folium.GeoJsonPopup(gdf.drop(columns=["geometry"]).columns.tolist()),
tooltip=folium.GeoJsonTooltip(["ref"]),
).add_to(m)
m

folium draw circle not drawing

I'm trying to draw some circles to outline koala sightings around Brisbane Aus. When I try and run it in jupyter, it draws the map and if I replace the coordinate[["decimalLatitude"],coordinate["decimalLongitude"]] with actual values, it displays, but otherwise it doesn't. Here's my code and a sample pic of the data.
import folium
map_of_koala_sightings = folium.Map(
location =[-27.470125,153.021072],
zoom_start=13, tiles='Stamen Terrain'
)
for coordinate in koala_df:
try:
folium.Circle(
radius=300,
location = coordinate[["decimalLatitude"],coordinate["decimalLongitude"]],
color='#3388ff',
fill=True).add_to(map_of_koala_sightings)
except:
pass
map_of_koala_sightings
Sample Data
This works for me (with a subset of coordinates).
import folium
import pandas as pd
koala_df = pd.DataFrame(columns = ['decimalLatitude','decimalLongitude'],
data = [[-26.770484,152.838467],
[-28.103458,153.375882],
[-26.4,146.25]])
print(koala_df.head())
map_of_koala_sightings = folium.Map(
location =[-27.470125,153.021072],
zoom_start=5, tiles='Stamen Terrain'
)
for idx,coordinate in koala_df.iterrows():
folium.Circle(radius=300,
location = [coordinate['decimalLatitude'],coordinate['decimalLongitude']],
color='#3388ff',
fill=True).add_to(map_of_koala_sightings)
#map_of_koala_sightings
#For saving to html file
map_of_koala_sightings.save('koalas.html')
Output:
decimalLatitude decimalLongitude
0 -26.770484 152.838467
1 -28.103458 153.375882
2 -26.400000 146.250000
and 'koalas.html' contains:

Python: k-means clustering

I’m trying to use k-means clustering for the data of longitudes and latitudes of a .csv file but instead of plotting a graph I only want to get and print the centroids so that i can search them on google maps. Does anyone know how to code that?
import pandas as pd
import numpy as np
import csv
with open('fileName.csv', 'r') as infile:
csv_reader = csv.reader (infile, delimiter=',')
x = []
y = []
for row in csv_reader:
if row[3] != 'LONGITUDE':
x.append(float(row[3]))
y.append(float(row[4]))
df = pd.DataFrame({
'x': x,
'y': y
})
#implement x and y in k-means and print the centroids
I would suggest looking at the Shapely library.
from shapely.geometry import MultiPoint
import pandas as pd
import numpy as np
import csv
# Easy way to read your csv file in
df = pd.read_csv('fileName.csv').rename(columns={'LONGITUDE': 'x', 'LATITUDE': 'y'})
# Assumes you have a column 'cluster_id' that references the cluster id for each coordinate
cluster_ids = df['cluster_id'].unique()
kmeans_clusters = []
for cluster_id in cluster_ids:
# Filtered df for each cluster id
cluster_df = df.loc[df['cluster_id'] == cluster_id]
x_values = cluster_df['x'].tolist()
y_values = cluster_df['y'].tolist()
xy_pairs = [point for point in zip(x_values, y_values)]
kmeans_clusters.append(xy_pairs)
# Where kmeans_clusters is a list of your clusters, each containing a list of xy pairs
centroids = []
for cluster in kmeans_clusters:
if len(cluster) > 1:
# Create a convex hull, find the centroid
convex_hull = MultiPoint(cluster).convex_hull
centroid = convex_hull.centroid
# Unpack to tuple object
centroids.append(list(centroid.coords)[0])
else:
# Single point cluster, it is the centroid
centroids.append(cluster[0])
print(centroids)

Convert DataFrame to a multi polygon DataFrame, multiple data point - python

I have a DataFrame as below, I want to convert data to a multi polygon DataFrame, because I want to plot each multi polygon on a map.
I know how to convert if I have two data point, but with 6 data point, I don't know how to convert it. can anyone help me please.
geometry = [Point(xy) for xy in zip(neightrip_counts_.lan0, neightrip_counts_.long0)]
geometry
#neightrip_counts_.lan1, neightrip_counts_.long1,neightrip_counts_.lan2, neightrip_counts_.long2
lan0 long0 lan1 long1 lan2 long2
0 59.915667 10.777567 59.916738 10.779916 59.914943 10.773977
1 59.929853 10.711515 59.929435 10.713682 59.927596 10.710033
2 59.939230 10.759170 59.937205 10.760581 59.943750 10.760306
3 59.912520 10.762240 59.911594 10.761774 59.912347 10.763815
4 59.929634 10.732839 59.927140 10.730981 59.931081 10.736003
Let me rename the dataframe neightrip_counts_ as df for brevity. Here is the relevant code that will create a polygon for each row of dataframe.
df['geometry'] = [Polygon([(z[0],z[1]), (z[2],z[3]), (z[4],z[5])]) for z in zip(df.long0, df.lan0, df.long1, df.lan1, df.long2, df.lan2)]
gpdf = df.set_geometry("geometry", drop=True)
gpdf.plot()
By the way, you must be careful about the sequence of (long, lat).
start_coords = [ gdf.centroid[0].x, gdf.centroid[0].y] # is wrong
Use this in stead.
start_coords = [ gdf.centroid[0].y, gdf.centroid[0].x]
Edit
For the benefits of the readers, here is the complete runnable code:
import pandas as pd
import geopandas as gpd
from io import StringIO
from shapely.geometry import Polygon, Point, LineString
import numpy as np
import folium
data1 = """index lan0 long0 lan1 long1 lan2 long2
0 59.915667 10.777567 59.916738 10.779916 59.914943 10.773977
1 59.929853 10.711515 59.929435 10.713682 59.927596 10.710033
2 59.939230 10.759170 59.937205 10.760581 59.943750 10.760306
3 59.912520 10.762240 59.911594 10.761774 59.912347 10.763815
4 59.929634 10.732839 59.927140 10.730981 59.931081 10.736003"""
# read/parse data into dataframe
df0 = pd.read_csv(StringIO(data1), sep='\s+', index_col='index')
# create `geometry` column
df0['geometry'] = [Polygon([(xy[0],xy[1]), (xy[2],xy[3]), (xy[4],xy[5])]) \
for xy in zip(df0.long0, df0.lan0, df0.long1, df0.lan1, df0.long2, df0.lan2)]
# set geometry
gpdf = df0.set_geometry("geometry", drop=True)
# do check plot. (uncomment next line)
#gpdf.plot()
# make geojson
center_pt = gpdf.centroid[0].y, gpdf.centroid[0].x
gdf_json = gpdf.to_json()
# plot the geojson on the folium webmap
webmap = folium.Map(location = center_pt, zoom_start = 13, min_zoom = 3)
folium.GeoJson(gdf_json, name='data_layer_1').add_to(webmap)
# this opens the webmap
webmap
Output screen capture (of interactive webmap):
Try this, assuming the 'lan' is latitude.
import geopandas as gpd
from shapely.geometry import Polygon
import numpy as np
import pandas as pd
import folium
# ....
def addpolygeom(row):
row_array = np.array(row)
# split dataframe row to a list of tuples (lat, lon)
coords = [tuple(i)[::-1] for i in np.split(row_array, range(2, row_array.shape[0], 2))]
polygon = Polygon(coords)
return polygon
# Convert points to shapely geometry
neightrip_counts_['geometry'] = neightrip_counts_.apply(lambda x: addpolygeom(x), axis=1)
# Create a GeoDataFrame
gdf = gpd.GeoDataFrame(neightrip_counts_, geometry='geometry')
start_coords = [ gdf.centroid[0].y, gdf.centroid[0].x]
gdf_json = gdf.to_json()
map = folium.Map(start_coords, zoom_start=4)
folium.GeoJson(gdf_json, name='mypolygons').add_to(map)

Categories