is it possible to use k-means on a folium map? - iPython - k-means

I have a map plotted with a list of coordinates
newmap = folium.Map(location=[52.667989, -1.464582], zoom_start=6, tiles='Stamen Terrain' )
for coord in new_latlonl:
la, lo = coord[0], coord[1]
newmap.polygon_marker(location=[la, lo], fill_color='#43d9de', radius=8)
newmap.create_map(path='newmap.html')
Is it possible to use k-means clustering on this?

Related

Is Cartopy capable of plotting georeferenced data from another planet (e.g., Mars, the Moon)?

I'm working with several data sets from the Moon and Mars (topography, crustal thickness) and was wondering if Cartopy can manipulate these data given the reference ellipsoids are different. Do custom ellipsoids need to be created, or are they built in to Cartopy?
I figured out how to do this on my own. Here's the solution I came up with...
Step 1
Import Cartopy...
import cartopy.crs as ccrs
After importing Cartopy and loading your data set, you need to change Cartopy's Globe class such that it does not use the WGS84 ellipse. Simply define new semi-major and semi-minor axes and tell Cartopy to refrain from using a terrestrial ellipse.
img_globe = ccrs.Globe(semimajor_axis = semimajor, semiminor_axis = semiminor, ellipse = None)
Step 2
Next, choose a map projection for plotting and identify your data's format. I decided to plot my data using a Mollweide coordinate system and found my data is defined in the Plate Carree coordinate system. Now we can define the map projection and coordinate system for the data using the new Globe class defined above.
projection = ccrs.Mollweide(globe = img_globe)
data_crs = ccrs.PlateCarree(globe = img_globe)
Step 3
Lastly, plot your data using standard Matplotlib syntax with two important caveats. First create axes that implement the map projection.
fig = plt.figure(figsize = (6,6))
ax = plt.axes(projection = projection)
When plotting the data, you have to inform Matplotlib how your data are formatted using the transform argument.
ax.imshow(data, extent = extent, cmap = 'viridis', transform = data_crs)
The end result looks like this...

How to plot the mean silhouette score for each cluster in matplotlib python

I have 78 rows and 131 columns and I need to plot the mean silhouette score for each cluster in python matplotlib as a line graph. I did these codes and worked great but I don't know how to plot?
mean = KMeans(n_clusters = 2)
kmean.fit(Data1)
centroids = kmean.cluster_centers_
print("Shape of Centroids Array: " + str(centroids.shape))
print()
print(centroids)
from collections import Counter
labels = kmean.labels_
c = Counter(labels)
print(c.most_common())
Record_array =Data1.values
print(Record_array)
mean_sihouette_score = ss(Record_array, labels)
print(mean_sihouette_score)
for cluster_number in range(0,2):
print("Cluster {} contains {} samples with percentage of {:.2f}%".format(cluster_number, c[cluster_number], c[cluster_number]/sum(c.values()) *100))
Coding to plot average silhouette score is not an easy job.
I usually have yellowbrick it done.
Here, you could take a look.
https://www.scikit-yb.org/en/latest/api/cluster/silhouette.html
or their code right here (please install yellowbrick beforehand)
from yellowbrick.cluster import SilhouetteVisualizer
model = KMeans(5, random_state=42)
visualizer = SilhouetteVisualizer(model, colors='yellowbrick')
visualizer.fit(X) # Fit the data to the visualizer
visualizer.show() # Finalize and render the figure

Cartopy plot high/low sea level pressure on map

I'm migrating from basemap to cartopy. One thing I would like to do is plot high/low pressure on a map, such as in basemap. There is a good example on this page of how to do this: https://matplotlib.org/basemap/users/examples.html ("Plot sea-level pressure weather map with labelled highs and lows"). I'm not going to copy and paste the code from this site, but would like to know how to do the same in cartopy. The main thing I can't get my head around is how to do m.xmax and x > m.xmin and y < m.ymax and y > m.ymin in cartopy (some kind of vector transform I'd imagine.
I've had a good look and can't see this particular example translated into something compatible with cartopy. Any help would be welcome!
In order to write an equivalent program using cartopy you need to be able to translate two concepts. The first is finding the extent of a projection, this can be done with the get_extent() method of a GeoAxes:
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
my_proj = ccrs.Miller(central_longitude=180)
ax = plt.axes(projection=my_proj)
xmin, xmax, ymin, ymax = ax.get_extent()
You also need to transform coordinate points from geographic to projection coordinates, which is the function of the transform_points() method of a coordinate reference system instance:
import numpy as np
lons2d, lats2d = np.meshgrid(lons, lats) # lons lats are in degrees
transformed = my_proj.transform_points(ccrs.Geodetic(), lons2d, lats2d)
x = transformed[..., 0] # lons in projection coordinates
y = transformed[..., 1] # lats in projection coordinates
Now you can use the same technique as in the basemap example to filter and plot points, where instead of m.xmin you use xmin etc.
There are of course alternate ways of doing this which have pros and cons relative to the basemap example. If you come up with something nice you can contribute it to the Cartopy gallery.

Pyplot polar surface plot

I am new in pyplot.
I have a Cartesian surface plot:
# offset and omega are arrays
Z = my_function(omega,offset) # my_function give and arrays of omega.size*offset.size
fig, ax = plt.subplots(1)
p = ax.pcolor(offset,omega,Z.T,cmap=cm.jet,vmin=abs(Z).min(),vmax=abs(Z).max())
cb = fig.colorbar(p,ax=ax)
Maybe there is a more simple way to plot a surface but that the way I've found on the internet.
Well, now I want to plot my_function as a surface using polar coordinate, I've tried this:
ax2 = plt.subplot(111, polar=True)
p2 = ax2.pcolor(offset,omega,Z.T,cmap=cm.jet,vmin=abs(Z).min(),vmax=abs(Z).max())
It kind of work, I have a surface plot but it does not take into account the limits of Y.
For example if Y is defined between -15 and 15° I only want my function to be plotted and shown between those angles and not 0 to 360° as my example is doing.
How can I do that ?
I thank you in advance for any answer.

Contour plotting orbitals in pyquante2 using matplotlib

I'm currently writing line and contour plotting functions for my PyQuante quantum chemistry package using matplotlib. I have some great functions that evaluate basis sets along a (npts,3) array of points, e.g.
from somewhere import basisset, line
bfs = basisset(h2) # Generate a basis set
points = line((0,0,-5),(0,0,5)) # Create a line in 3d space
bfmesh = bfs.mesh(points)
for i in range(bfmesh.shape[1]):
plot(bfmesh[:,i])
This is fast because it evaluates all of the basis functions at once, and I got some great help from stackoverflow here and here to make them extra-nice.
I would now like to update this to do contour plotting as well. The slow way I've done this in the past is to create two one-d vectors using linspace(), mesh these into a 2D grid using meshgrid(), and then iterating over all xyz points and evaluating each one:
f = np.empty((50,50),dtype=float)
xvals = np.linspace(0,10)
yvals = np.linspace(0,20)
z = 0
for x in xvals:
for y in yvals:
f = bf(x,y,z)
X,Y = np.meshgrid(xvals,yvals)
contourplot(X,Y,f)
(this isn't real code -- may have done something dumb)
What I would like to do is to generate the mesh in more or less the same way I do in the contour plot example, "unravel" it to a (npts,3) list of points, evaluate the basis functions using my new fast routines, then "re-ravel" it back to X,Y matrices for plotting with contourplot.
The problem is that I don't have anything that I can simply call .ravel() on: I either have 1d meshes of xvals and yvals, the 2D versions X,Y, and the single z value.
Can anyone think of a nice, pythonic way to do this?
If you can express f as a function of X and Y, you could avoid the Python for-loops this way:
import matplotlib.pyplot as plt
import numpy as np
def bf(x, y):
return np.sin(np.sqrt(x**2+y**2))
xvals = np.linspace(0,10)
yvals = np.linspace(0,20)
X, Y = np.meshgrid(xvals,yvals)
f = bf(X,Y)
plt.contour(X,Y,f)
plt.show()
yields