Currently I have the following script that generates a polar plot of azimuth/radius data. "R1" is simple a list of values of [azimuth, inclination] derived from a table in ArcGIS.
import matplotlib.pyplot as plt
import numpy as np
for(a,r) in R1:
angles.append(a)
radius.append(90-r)
theta = np.radians(angles)
r = radius
ax = plt.subplot(111,polar=True)
ax.plot(theta, r, color='black', ls='-', linewidth=1)
ax.fill(theta,r,'0.75') ## should I use ax.fill_betweenx() ?
ax.set_theta_zero_location('N')
ax.set_theta_direction(-1)
ax.set_rmax(90)
ax.set_rmin(0)
ax.set_yticks(range(0,90,10))
yLabel=['90','','','60','','','30','','','']
ax.set_yticklabels(yLabel)
ax.grid(True)
plt.show()
At the moment this creates the following plot:
How can I "invert" the fill so that what is filled with gray will be white, and what is white will be gray?
I have tried ax.fill_betweenx(theta,90,r,color='0.75') and that didn't work. I have been battling with this for some time now to no avail.
ANY help or suggestions are greatly appreciated!
If there is any way I can make this clearer, please let me know in the comments.
Depending on what you want to do with this later, the quickest way is to simply make the background gray and the fill white:
import matplotlib.pyplot as plt
import numpy as np
ax = plt.subplot(111, polar=True)
theta = np.linspace(0, 2*np.pi, 100)
r = 2 + np.sin(theta * 2)
ax.patch.set_facecolor('0.5')
ax.plot(theta, r, color='black', ls='-', linewidth=1)
ax.fill(theta,r,'w')
plt.show()
plt.draw() # just to be safe!
Related
I am making a figure with subplots which are north polar stereographic projections. I also created a custom boundary shape to display subplot as a circle. However once reprojected, I want to be able to rotate the map, since my data is focusing on the US and thus I was hoping that each subplot would have the US facing "up," thus I would need to rotate it 270 degrees / -90 degrees.
Minimalistic code example pulled from cartopy example
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline # for notebook
map_projection = ccrs.NorthPolarStereo(central_longitude=0, )
data_projection = ccrs.PlateCarree()
theta = np.linspace(0, 2*np.pi, 100)
center, radius = [0.5, 0.5], 0.5 # by changing radius we can zoom in/out
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
circle = mpl.path.Path(verts * radius + center)
plot_extent=[-179.9,180, 30, 90]
fig, ax1 = plt.subplots(1,1, figsize=(6,6), dpi=100, subplot_kw=dict(projection=map_projection))
ax1.set_boundary(circle, transform=ax1.transAxes)
ax1.coastlines(linewidths=1.0, color='grey')
ax1.add_feature(cfeature.BORDERS, linestyles='--', color='dimgrey', linewidths=0.8 )
ax1.set_extent(plot_extent, crs=ccrs.PlateCarree(),)
gl = ax1.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
linewidth=1, color='gray', alpha=0.5, linestyle='--', zorder=10)
I haven't yet found any good examples or documentation for what I am trying to do, however I am new to using matplotlib/cartopy.
You need to set central_longitude=-90.
So:
map_projection = ccrs.NorthPolarStereo(central_longitude=-90)
How can I make that when I plot a function (based on a np.array) certain values have their coordinates in the plot?
I know how to change color and other little things with code lines like:
line1, = plt.plot(t, f, '*-', label='force', color='#4F81BD') # blue
line2, = plt.plot(t, a, 'o-', label='acceleration', color='#C0504D') # red
but for example if I have a "peak" in the plot line, I don't know how to make their coordinates to appear in the same plot
This code snippet might help you:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x=[1,2,3,4,5,6,7,8,9,10]
y=[1,1,1,2,10,2,1,1,1,1]
line, = ax.plot(x, y)
ymax = max(y)
xpos = y.index(ymax)
xmax = x[xpos]
#Labeling the graph (ymax+1 is defining the distance from the word to the point)
ax.annotate('local max', xy=(xmax, ymax), xytext=(xmax, ymax+1))
ax.set_ylim(0,20)
plt.show()
Output:
I hope I could help you out a bit.
I haven't found an answer to this yet: I have a grid defined in a text file with four columns: (lon,lat,depth,slip). Each row is a grid point.
I can generate a scatter plot of these points using the following simple code:
# Main imports:
import numpy as np
from pylab import *
from mpl_toolkits.mplot3d import Axes3D
# Read the grid:
points = np.loadtxt("grid.txt")
# Retrieve parameters from the grid:
lon = points[:,0]
lat = points[:,1]
depth = points[:,2]
slip = points[:,3]
# 3-D plot of the model:
fig = figure(1)
ax = fig.add_subplot(111, projection='3d')
p = ax.scatter(lon, lat, depth, c=slip, vmin=0, vmax=max(slip), s=30, edgecolor='none', marker='o')
fig.colorbar(p)
title("Published finite fault in 3-D")
ax.set_xlabel("Longitude [degrees]")
ax.set_ylabel("Latitude [degrees]")
ax.set_zlabel("Depth [km]")
ax.invert_zaxis()
jet()
grid()
show()
And I get the following figure:
What I want to do is to be able to interpolate those points to create a "continuous" surface grid and plot it in both 2-D and 3-D plots. Therefore, somehow I've to consider all (lon,lat,depth,slip) in the interpolation. I'd appreciate your suggestions. Thanks in advance!
I'm a bit late, but if your data grid is properly ordered, you could resolve your iusse using plot_surface reshaping your 1D data to 2D.
An example supposing you're using a 10x10 grid:
# Main imports:
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
# Set the fourth dimension`
color_dimension = slip.reshape(10,10)
# normalize the colours
minn, maxx = color_dimension.min(), color_dimension.max()
norm = matplotlib.colors.Normalize(minn, maxx)
# color map
m = plt.cm.ScalarMappable(norm=norm, cmap='hot')
m.set_array([])
fcolors = m.to_rgba(color_dimension)
# plot
fig = plt.figure()
ax = fig.gca(projection='3d')
#reshape 1D data to 2D
g=ax.plot_surface(lat.reshape(10, 10), lon.reshape(10, 10), depth.reshape(10, 10), cmap='hot',rstride=1, cstride=1, facecolors=fcolors, vmin=minn, vmax=maxx, shade=False)
cbar=fig.colorbar(g,aspect=50)
cbar.set_label('slip', rotation=270, fontsize=14)
title("Published finite fault in 3-D")
ax.set_xlabel("Longitude [degrees]")
ax.set_ylabel("Latitude [degrees]")
ax.set_zlabel("Depth [km]")
ax.invert_zaxis()
plt.show()
I'm trying to plot a polar plot with this code:
import numpy as np
import matplotlib.pylab as plt
def power(angle, l, lam):
return 1/(lam) * ((np.cos(np.pi*l*np.cos(angle)/lam) - np.cos(np.pi*l/lam))/np.sin(angle))**2
fig = plt.figure(1)
ax = fig.add_subplot(111, projection='polar')
theta = np.linspace(0.001, 2*np.pi, 100)
P1 = power(theta, 1, 5)
ax.plot(theta, P1, color='r', linewidth=3)
plt.savefig('1.png')
and I get this plot:
I would like to change 2 things. The first and more important one is to hide the radial tick labels (I just want to show the general form of the plot).
If possible, how can I choose the vertical axis to correspond to 0°?
Thanks for your help.
You can use set_yticklabels() to remove the radial ticks and set_theta_zero_location() to change the zero location:
fig = plt.figure(1)
ax = fig.add_subplot(111, projection='polar')
ax.plot(theta, P1, color='r', linewidth=3)
ax.set_yticklabels([])
ax.set_theta_zero_location('N')
plt.show()
You might also want to change the direction of the azimuthal axis:
ax.set_theta_direction(-1)
You can set the theta zero position with ax.set_theta_zero_location('N').
To modify the r tick labels, you could do something like
for r_label in ax.get_yticklabels():
r_label.set_text('')
If you want to remove them entirely, do ax.set_yticklabels([]).
More methods can be found in the PolarAxes documentation.
I am using matplotlib to make some plots and I have run into a few difficulties that I need help with.
problem 1) In order to keep a consistent colorscheme I need to only use half of the color axis. There are only positive values, so I want the zero values to be green, the mid values to be yellow and the highest values to be red. The color scheme that most closely matches this is gist_rainbow_r, but I only want the top half of it.
problem 2) I can't seem to figure out how to get the colorbar on the right hand side of the plot to show up or how to get it to let me label the axes.
If it helps, I am using the latest version of Anaconda wth the latext version of matplotlib
cmap = plt.get_cmap('gist_rainbow_r')
edosfig2 = plt.figure(2)
edossub2 = edosfig.add_subplot(1,1,1)
edossub2 = plt.contourf(eVec,kints,smallEDOS,cmap=cmap)
edosfig2.show()
If you have a specific set of colors that you want to use for you colormap, you can build it based on those. For example:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
cmap = LinearSegmentedColormap.from_list('name', ['green', 'yellow', 'red'])
# Generate some data similar to yours
y, x = np.mgrid[-200:1900, -300:2000]
z = np.cos(np.hypot(x, y) / 100) + 1
fig, ax = plt.subplots()
cax = ax.contourf(x, y, z, cmap=cmap)
cbar = fig.colorbar(cax)
cbar.set_label('Z-Values')
plt.show()
However, if you did just want the top half of some particularly complex colormap, you can copy a portion of it by evaluating the colormap over the range you're interested in. For example, if you wanted the "top" half, you'd evaluate it from 0.5 to 1:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
# Evaluate an existing colormap from 0.5 (midpoint) to 1 (upper end)
cmap = plt.get_cmap('gist_earth')
colors = cmap(np.linspace(0.5, 1, cmap.N // 2))
# Create a new colormap from those colors
cmap2 = LinearSegmentedColormap.from_list('Upper Half', colors)
y, x = np.mgrid[-200:1900, -300:2000]
z = np.cos(np.hypot(x, y) / 100) + 1
fig, axes = plt.subplots(ncols=2)
for ax, cmap in zip(axes.flat, [cmap, cmap2]):
cax = ax.imshow(z, cmap=cmap, origin='lower',
extent=[x.min(), x.max(), y.min(), y.max()])
cbar = fig.colorbar(cax, ax=ax, orientation='horizontal')
cbar.set_label(cmap.name)
plt.show()