I have a figure object returned by a function.
import numpy as np
from scipy.spatial import Voronoi, voronoi_plot_2d, Delaunay
import shapely.geometry
import shapely.ops
points = np.random.random((20, 2))
print(points)
vor = Voronoi(points)
fig = voronoi_plot_2d(vor, show_vertices=True, show_points=True)
fig.add
plt.show()
print(vor.ridge_points)
print(vor.ridge_points[1,0])
print(vor.ridge_points[1,1])
plt.plot(points[vor.ridge_points[1,0]], points[vor.ridge_points[1,1]])
plt.show()
I would like to overlay fig
on another plot created in the line
plt.plot(points[vor.ridge_points[1,0]], points[vor.ridge_points[1,1]])
Suggestions on how to visualize both the plots in a single figure will be helpful.
You should create a fig, ax object, and pass the ax argument to the voronoi_plot_2d as suggested in the comments by #Jody Klymak, like:
import numpy as np
from scipy.spatial import Voronoi, voronoi_plot_2d, Delaunay
import shapely.geometry
import shapely.ops
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
points = np.random.random((20, 2))
print(points)
vor = Voronoi(points)
voronoi_plot_2d(vor, show_vertices=True, show_points=True, ax=ax)
print(vor.ridge_points)
print(vor.ridge_points[1,0])
print(vor.ridge_points[1,1])
ax.plot(points[vor.ridge_points[1,0]], points[vor.ridge_points[1,1]])
plt.show()
Related
Is it possible to create something like the picture? cause I just can't get it to work. Mine isn't showing shapes on the grid for some reason. Any help would be appreciated
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle
import matplotlib.patches as mpatches
# Data for plotting
fig, ax = plt.subplots(1,figsize=(8,7))
#use add_patch instead, it's more clear what you are doing
ax.plot([1,5,2],[2,3,4],color="cyan")
rect = Rectangle((5,5),6,6, fill= False)
plt.gca().add_patch(rect)
ax.add_patch(rect)
plt.ylim(1400,2300)
plt.xlim(34,48)
plt.xlabel("inches")
plt.ylabel("weight (lbs)")
plt.title('Váha a vyváženie lietadla Cessna 172N')
plt.legend(["Utility","Normal category"])
plt.grid()
plt.plot
plt.show()
This code is from Basemap docs pages, with some changing to focus on my issue at hand.
I want to color(in this case, magenta) all lands(Antarctica can be overlooked), and all ocean should be white like Antarctica is right now. The shapefile is from here
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
from matplotlib.patches import PathPatch
import numpy as np
fig = plt.figure(figsize=(20,20))
ax = fig.add_subplot(111)
map = Basemap(llcrnrlon=-180,llcrnrlat=-85,urcrnrlon=180.,urcrnrlat=85, projection='merc')
map.readshapefile('countries_lakes/ne_10m_admin_0_countries_lakes', 'units')
patches = []
for info, shape in zip(map.units_info, map.units):
patches.append(Polygon(np.array(shape), True))
ax.add_collection(PatchCollection(patches, facecolor= 'm', edgecolor='k', linewidths=1.))
plt.savefig('dem.png', bbox_inches='tight')
I have two polygons (one rectangle and one triangle), I want to have a function (poly_intersect) that gives me the intersection between these two polygons.
related image is here
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
polygon1 = pd.DataFrame([[2,2],[4,2],[4,4],[2,4],[2,2]],columns=['X','Y'])
polygon2 = pd.DataFrame([[1,3],[3,3],[3,6],[1,3]],columns=['X','Y'])
fig, ax = plt.subplots(1,1, figsize=(6, 4))
ax.add_patch(matplotlib.patches.Polygon(polygon1.values,color='blue',alpha=0.5))
ax.add_patch(matplotlib.patches.Polygon(polygon2.values,color='green',alpha=0.5))
ax.axis([0,5,1,7])
vertices = poly_intersect(polygon1,polygon2)
expected output: [[2,3],[3,3],[3,4],[2,4]]
In the example below, I create a rectangular patch using matplotlib.patches.Polygon. Is there a way to scale the patch before adding it to the plot?
I've tried using matplotlib.transforms.Affine2D in a variety of ways with no success. As usual, the matplotlib documentation on transformations is woefully insufficient.
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot([-3,3],[-3,3])
x = [-1,0,1,1,0,-1]
y = [1,1,1,-1,-1,-1]
poly = Polygon( zip(x,y), facecolor='red', edgecolor='red', alpha=0.5)
ax.add_patch(poly)
plt.show()
If by scale you mean multiplication by a factor, you can easily do this via numpy.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot([-3,3],[-3,3])
x = [-1,0,1,1,0,-1]
y = [1,1,1,-1,-1,-1]
scale = 2
poly = Polygon( np.c_[x,y]*scale, facecolor='red', edgecolor='red', alpha=0.5)
ax.add_patch(poly)
plt.show()
The same can be achieved with a matplotlib.transforms.Affine2D() transform.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import matplotlib.transforms as transforms
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot([-3,3],[-3,3])
x = [-1,0,1,1,0,-1]
y = [1,1,1,-1,-1,-1]
trans = transforms.Affine2D().scale(2) + ax.transData
poly = Polygon( np.c_[x,y], facecolor='red', edgecolor='red', alpha=0.5,
transform=trans)
ax.add_patch(poly)
plt.show()
Although it seems a bit overkill for a simple scaling like this.
I have the following script
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(24,7)
heatmap = plt.pcolor(data)
plt.show()
Which results into this image
How can I remove the white bar at the very top?
You have to manually set the x and y limits sometimes when you're using pcolor.
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(24,7)
heatmap = plt.pcolor(data)
plt.ylim(0, 24)
plt.show()
I am assuming here that your matrix is not a jagged matrix:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(24,7)
nrow, ncol = data.shape
heatmap = plt.pcolor(data)
# put the major ticks
heatmap.axes.set_xticks(np.arange(ncol), minor=False)
heatmap.axes.set_yticks(np.arange(nrow), minor=False)
heatmap.axes.set_xlim(0,ncol) # Assuming a non jagged matrix
heatmap.axes.set_ylim(0,nrow)
plt.show()
Just simple change. np.random.rand(24,7) replace to np.random.rand(25,7)
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(25,7)
heatmap = plt.pcolor(data)
plt.show()
Output:
Or add axis Like plt.axis([0,7,0,24])
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(24,7)
heatmap = plt.pcolor(data)
plt.axis([0,7,0,24])
plt.show()
Output: