I'm plotting some filled contours with Cartopy and Matplotlib. The data is on a latitude/longitude grid, and when plotting on a cartopy projection, a white line runs down the middle of the figure, or wherever I set "central_longitude" into in ccrs.PlateCarree()
Here is a quick setup that shows what I'm talking about. Using the code:
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
lon = np.arange(0, 360, 1)
lat = np.arange(-90, 90, 1)
data = np.zeros((180, 360))
fig = plt.figure()
ax = plt.subplot(projection=ccrs.PlateCarree())
ax.contourf(lon, lat, data)
ax.add_feature(cfeature.COASTLINE.with_scale('50m'))
plt.show()
Which produces the image:
Is there a way to remove this white line?
You should use cartopy.util.add_cyclic_point so that contourf sees the data as continuous in the x-direction and the white line will disappear:
import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.util import add_cyclic_point
lon = np.arange(0, 360, 1)
lat = np.arange(-90, 90, 1)
data = np.zeros((180, 360))
data, lon = add_cyclic_point(data, coord=lon)
fig = plt.figure()
ax = plt.subplot(projection=ccrs.PlateCarree())
ax.contourf(lon, lat, data)
ax.add_feature(cfeature.COASTLINE.with_scale('50m'))
plt.show()
Related
I'm having an issue with using cartopy in Python to plot the longitude and latitude of datapoints onto a world map.
However, the resulting world map is inverted but the data points are correct.
Adding the link to the dataFrame here as it is too large to display here (clean_countryData1)
# Plotting world map
! pip install cartopy
import matplotlib.pyplot as plt
import seaborn as sb
import cartopy.crs as ccrs
import cartopy.crs as ccrs
import cartopy.feature as cf
fig = plt.figure(figsize = (40, 20))
ax = fig.add_subplot(1, 1, 1,
projection = ccrs.PlateCarree())
ax.add_feature(cf.LAND)
ax.add_feature(cf.OCEAN)
ax.add_feature(cf.COASTLINE)
ax.add_feature(cf.BORDERS, linestyle = ':')
ax.add_feature(cf.LAKES, alpha = 0.5)
ax.add_feature(cf.RIVERS)
ax.set_title("Aircraft Accidents Around The World",
fontsize = 40)
sb.scatterplot(x = "LONGITUDE", y = "LATITUDE",
data = clean_countryData,
hue = "INJURY_SEVERITY",
alpha = 0.8,
marker = 'o',
s = 100,
color = "red",
transform = ccrs.PlateCarree())
plt.show()
What I got:
Expected result:
In the chamber measurement, Theta varies from -180:180 and phi varies from 0:180. I have to plot theta from 0:180 and phi from 0:360. How can I plot that in python without altering the dataset file but just in code?
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from mpl_toolkits import mplot3d
import pandas as pd
from matplotlib import rcParams
df= pd.read_csv('Data.csv')
df.head()
Z=df.pivot(index="Phi", columns="Theta", values="E_total").T.values
X_unique = np.sort(df.Theta.unique())
Y_unique = np.sort(df.Phi.unique())
X, Y = np.meshgrid(X_unique, Y_unique)
fig = plt.figure()
ax = fig.add_subplot(111)
cpf = ax.contourf(X,Y,Z,20, cmap=cm.jet)
plt.colorbar(cpf)
ax.set_xlabel('Phi')
ax.set_ylabel('Theta')
enter image description here
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()
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 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: