I have data for few points along the polar coordinates. The data is aligned as shown below
Data
I need help in plotting a 2D polar plot as shown below. I cant understand how do I reshape the values needed to plot contour plot.
enter image description here
Borrowed this code to modify and use for my test case :
theta = np.radians(azimuths)
zeniths = np.array(zeniths)
values = np.array(values)
values = values.reshape((len(azimuths), len(zeniths)))
r, theta = np.meshgrid(zeniths, np.radians(azimuths))
print(r,theta)
print(r.shape)
print(theta.shape)
fig, ax = subplots(subplot_kw=dict(projection='polar'))
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
autumn()
cax = ax.contourf(theta, r, values, 30)
autumn()
cb = fig.colorbar(cax)
return fig, ax, cax
Related
I am writing a program that displays a heat map of lightning strikes over a cartopy plot. Using a scatter plot work; however when I try to implement the 2d histogram, the map becomes zoomed out all the way.
Plot before adding histogram
Plot after adding histogram
Here is the code
lon_small and lat_small are the coordinate arrays.
proj = ccrs.LambertConformal()
fig, ax = plt.subplots(figsize=(10,10),subplot_kw=dict(projection=proj))
#FEATURES
#state_borders = cfeat.NaturalEarthFeature(category='cultural', name="admin_1_states_provinces_lakes", scale = '10m', facecolor = 'none')
extent = ([-99,-92, 27, 31.3])
xynps = ax2.projection.transform_points(ccrs.PlateCarree(), lon_array, lat_array)
ax.set_extent(extent)
ax.set_extent(extent)
ax.add_feature(USCOUNTIES.with_scale('5m'), edgecolor = "gray")
ax.add_feature(state_borders, linestyle='solid', edgecolor='black')
ax.gridlines(draw_labels=True, dms=True, x_inline=False, y_inline=False)
#Adding scatter plots
ax.scatter(-95.36, 29.76, transform = ccrs.PlateCarree(), marker='*', s = 400, color = "orange") #Houston
ax.scatter(lon_small, lat_small, transform = ccrs.PlateCarree(), marker='.', s=0.001, c = "red")
#Adding Histogram
h = ax.hist2d(xynps[:,0], xynps[:,1], bins=100, zorder=10, alpha=0.75, cmin=120)
plt.show()
I have checked online for people with a similar problem, but I can't find anything like this problem.
There's a note in the docstring of hist2d stating:
Currently hist2d calculates its own axis limits, and any limits previously set are ignored.
... so i guess the easiest way to maintain initial limits is to do something like this:
...
extent = ax.get_extent(crs=ax.projection)
ax.hist2d(...)
ax.set_extent(extent, crs=ax.projection)
...
I have three dataset xx, yy, tau, for which I would like to realize a 2D plot.
Hence, I produce the following code, which return a contour plot by tricontourf. In particular at each value of tau(i), a given value of xx(i), yy(i) is associated.
fig, ax = plt.subplots(figsize = (10,8))
ax.set_xlabel('$\lambda$', fontsize=22)
ax.set_ylabel('$l_0$', fontsize = 22)
tcf = ax.tricontourf(xx, yy, tau, levels = 100)
cbar = fig.colorbar(tcf)
cbar.set_label(' \u03C4$_k$', fontsize =22)
plt.show()
All good for now. But how can I plot the value of tau simply as points/ dashed lines within this contour plot?
Background
Using an CNN autoencoder, I observe the projection of the latent space of a dataset of images. I'd like to hover over the 2D scatter plot and display the corresponding image. I also have the images true labels and would like to have it as legend (color scatter points).
Setup
My original images are contained in a 3D array X_plot, my PCA reduced dataset is in X, and I have a series of labels corresponding to the images in y.
X_plot.shape = (n, 64, 64) # n images of 64x64
X.shape = (n, 2) # list of 2D coordinates for each image
y.shape = (n, ) # n labels
# Example code to reproduce
from matplotlib import pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import numpy as np
n = 20
num_classes = 4
X_plot = np.random.rand(n, 64, 64)
X = np.random.rand(n, 2)
y = np.random.randint(num_classes, size=n)
Current code
Scatter with image display on hovering
This is largely inspired from this answer on StackOverFlow.
# Split 2D coordinates into list of xs and ys
xx, yy = zip(*X)
# create figure and plot scatter
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot(xx, yy, ls="", marker=".")
# create the annotations box
im = OffsetImage(X_plot[0,:,:], zoom=1, cmap='gray')
xybox=(50., 50.)
ab = AnnotationBbox(im, (0,0), xybox=xybox, xycoords='data',
boxcoords="offset points", pad=0.3, arrowprops=dict(arrowstyle="->"))
# add it to the axes and make it invisible
ax.add_artist(ab)
ab.set_visible(False)
def hover(event):
# if the mouse is over the scatter points
if line.contains(event)[0]:
# find out the index within the array from the event
ind, = line.contains(event)[1]["ind"]
# get the figure size
w,h = fig.get_size_inches()*fig.dpi
ws = (event.x > w/2.)*-1 + (event.x <= w/2.)
hs = (event.y > h/2.)*-1 + (event.y <= h/2.)
# if event occurs in the top or right quadrant of the figure,
# change the annotation box position relative to mouse.
ab.xybox = (xybox[0]*ws, xybox[1]*hs)
# make annotation box visible
ab.set_visible(True)
# place it at the position of the hovered scatter point
ab.xy =(xx[ind], yy[ind])
# set the image corresponding to that point
im.set_data(X_plot[ind,:,:])
else:
#if the mouse is not over a scatter point
ab.set_visible(False)
fig.canvas.draw_idle()
# add callback for mouse moves
fig.canvas.mpl_connect('motion_notify_event', hover)
plt.show()
Scatter with legend
If I want to display the 2D scatter with points colored and labeled with y, I use the following code:
fig = plt.figure()
ax = fig.add_subplot(111)
labels = np.unique(y)
for label in labels:
filtered_by_label = X[y == label]
ax.scatter(*zip(*filtered_by_label), s=12, marker='.', alpha=0.9, label=label)
ax.legend()
ax.axis('off')
Challenge
I can't get the two pieces of code above merged together. ax.plot doesn't seem to accept a legend list as argument. Using the labels loop in the 2nd sub-solution, I would need to create the line object that is used in the hover function. However, I looked into merging several of them without success.
Any tips? Thanks!
I found a workaround by overlaying my two plots.
In the following section (scatter with hover):
ax = fig.add_subplot(111)
line, = ax.plot(xx, yy, ls="", marker=".")
simply add the multiple scatter plots with legend.
ax = fig.add_subplot(111)
line, = ax.plot(xx, yy, ls="", marker="") # no marker for this one
labels = np.unique(y)
for label in labels:
filtered_by_label = X[y == label]
ax.scatter(*zip(*filtered_by_label), s=12, marker='.', alpha=0.9, label=label)
The line object is still accessible by the hover function, and points are displayed in color!
I'm having some trouble with color maps. Basically, what I would like to produce is similar to the image below.
On the bottom subplot I would like to be able to plot the relevant colour, but spanning the entire background of the subplot.i.e it would just look like a colourmap over the entire plot, with no lines or points plotted. It should still correspond to the colours shown in the scatter plot.
Is it possible to do this? what I would ideally like to do is put this background under the top subplot. ( the y scales are in diferent units)
Thanks for and help.
code for bottom scatter subplot:
x = np.arange(len(wind))
y = wind
t = y
plt.scatter(x, y, c=t)
where wind is a 1D array
You can use imshow to display your wind array. It needs to be reshaped to a 2D array, but the 'height' dimensions can be length 1. Setting the extent to the dimensions of the top axes makes it align with it.
wind = np.random.randn(100) + np.random.randn(100).cumsum() * 0.5
x = np.arange(len(wind))
y = wind
t = y
fig, ax = plt.subplots(2,1,figsize=(10,6))
ax[0].plot(x,y)
ax[1].plot(x, 100- y * 10, lw=2, c='black')
ymin, ymax = ax[1].get_ybound()
xmin, xmax = ax[1].get_xbound()
im = ax[1].imshow(y.reshape(1, y.size), extent=[xmin,xmax,ymin,ymax], interpolation='none', alpha=.5, cmap=plt.cm.RdYlGn_r)
ax[1].set_aspect(ax[0].get_aspect())
cax = fig.add_axes([.95,0.3,0.01,0.4])
cb = plt.colorbar(im, cax=cax)
cb.set_label('Y parameter [-]')
If you want to use it as a 'background' you should first plot whatever you want. Then grab the extent of the bottom plot and set it as an extent to imshow. You can also provide any colormap you want to imshow by using cmap=.
I try to plot two polar plots in one figure. See code below:
fig = super(PlotWindPowerDensity, self).get_figure()
rect = [0.1, 0.1, 0.8, 0.8]
ax = WindSpeedDirectionAxes(fig, rect)
self.values_dict = collections.OrderedDict(sorted(self.values_dict.items()))
values = self.values_dict.items()
di, wpd = zip(*values)
wpd = np.array(wpd).astype(np.double)
wpdmask = np.isfinite(wpd)
theta = self.radar_factory(int(len(wpd)))
# spider plot
ax.plot(theta[wpdmask], wpd[wpdmask], color = 'b', alpha = 0.5)
ax.fill(theta[wpdmask], wpd[wpdmask], facecolor = 'b', alpha = 0.5)
# bar plot
ax.plot_bar(table=self.table, sectors=self.sectors, speedbins=self.wpdbins, option='wind_power_density', colorfn=get_sequential_colors)
fig.add_axes(ax)
return fig
The length of the bar is the data base (how many sampling points for this sector). The colors of the bars show the frequency of certain value bins (eg. 2.5-5 m/s) in the correspondent sector (blue: low, red: high). The blue spider plot shows the mean value for each sector.
In the shown figure, the values of each plot are similar, but this is rare. I need to assign the second plot to another axis and show this axis in another direction.
EDIT:
After the nice answer of Joe, i get the result of the figure.
That's almost everything i wanted to achieve. But there are some points i wasn't able to figure out.
The plot is made for dynamicly changing data bases. Therefore i need a dynamic way to get the same location of the circles. Till now I solve it with:
start, end = ax2.get_ylim()
ax2.yaxis.set_ticks(np.arange(0, end, end / len(ax.yaxis.get_ticklocs())))
means: for second axis i alter the ticks in order to fit the ticklocs to the one's of first axis.
In most cases i get some decimal places, but i don't want that, because it corrupts the clearness of the plot. Is there a way to solve this problem more smartly?
The ytics (the radial one's) range from 0 to the next-to-last circle. How can i achieve that the values range from the first circle to the very last (the border)? The same like for the first axis.
So, as I understand it, you want to display data with very different magnitudes on the same polar plot. Basically you're asking how to do something similar to twinx for polar axes.
As an example to illustrate the problem, it would be nice to display the green series on the plot below at a different scale than the blue series, while keeping them on the same polar axes for easy comparison.:
import numpy as np
import matplotlib.pyplot as plt
numpoints = 30
theta = np.linspace(0, 2*np.pi, numpoints)
r1 = np.random.random(numpoints)
r2 = 5 * np.random.random(numpoints)
params = dict(projection='polar', theta_direction=-1, theta_offset=np.pi/2)
fig, ax = plt.subplots(subplot_kw=params)
ax.fill_between(theta, r2, color='blue', alpha=0.5)
ax.fill_between(theta, r1, color='green', alpha=0.5)
plt.show()
However, ax.twinx() doesn't work for polar plots.
It is possible to work around this, but it's not very straight-forward. Here's an example:
import numpy as np
import matplotlib.pyplot as plt
def main():
numpoints = 30
theta = np.linspace(0, 2*np.pi, numpoints)
r1 = np.random.random(numpoints)
r2 = 5 * np.random.random(numpoints)
params = dict(projection='polar', theta_direction=-1, theta_offset=np.pi/2)
fig, ax = plt.subplots(subplot_kw=params)
ax2 = polar_twin(ax)
ax.fill_between(theta, r2, color='blue', alpha=0.5)
ax2.fill_between(theta, r1, color='green', alpha=0.5)
plt.show()
def polar_twin(ax):
ax2 = ax.figure.add_axes(ax.get_position(), projection='polar',
label='twin', frameon=False,
theta_direction=ax.get_theta_direction(),
theta_offset=ax.get_theta_offset())
ax2.xaxis.set_visible(False)
# There should be a method for this, but there isn't... Pull request?
ax2._r_label_position._t = (22.5 + 180, 0.0)
ax2._r_label_position.invalidate()
# Ensure that original axes tick labels are on top of plots in twinned axes
for label in ax.get_yticklabels():
ax.figure.texts.append(label)
return ax2
main()
That does what we want, but it looks fairly bad at first. One improvement would be to the tick labels to correspond to what we're plotting:
plt.setp(ax2.get_yticklabels(), color='darkgreen')
plt.setp(ax.get_yticklabels(), color='darkblue')
However, we still have the double-grids, which are rather confusing. One easy way around this is to manually set the r-limits (and/or r-ticks) such that the grids will fall on top of each other. Alternately, you could write a custom locator to do this automatically. Let's stick with the simple approach here:
ax.set_rlim([0, 5])
ax2.set_rlim([0, 1])
Caveat: Because shared axes don't work for polar plots, the implmentation I have above will have problems with anything that changes the position of the original axes. For example, adding a colorbar to the figure will cause all sorts of problems. It's possible to work around this, but I've left that part out. If you need it, let me know, and I'll add an example.
At any rate, here's the full, stand-alone code to generate the final figure:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1977)
def main():
numpoints = 30
theta = np.linspace(0, 2*np.pi, numpoints)
r1 = np.random.random(numpoints)
r2 = 5 * np.random.random(numpoints)
params = dict(projection='polar', theta_direction=-1, theta_offset=np.pi/2)
fig, ax = plt.subplots(subplot_kw=params)
ax2 = polar_twin(ax)
ax.fill_between(theta, r2, color='blue', alpha=0.5)
ax2.fill_between(theta, r1, color='green', alpha=0.5)
plt.setp(ax2.get_yticklabels(), color='darkgreen')
plt.setp(ax.get_yticklabels(), color='darkblue')
ax.set_ylim([0, 5])
ax2.set_ylim([0, 1])
plt.show()
def polar_twin(ax):
ax2 = ax.figure.add_axes(ax.get_position(), projection='polar',
label='twin', frameon=False,
theta_direction=ax.get_theta_direction(),
theta_offset=ax.get_theta_offset())
ax2.xaxis.set_visible(False)
# There should be a method for this, but there isn't... Pull request?
ax2._r_label_position._t = (22.5 + 180, 0.0)
ax2._r_label_position.invalidate()
# Bit of a hack to ensure that the original axes tick labels are on top of
# whatever is plotted in the twinned axes. Tick labels will be drawn twice.
for label in ax.get_yticklabels():
ax.figure.texts.append(label)
return ax2
if __name__ == '__main__':
main()
Just to add onto #JoeKington 's (great) answer, I found that the "hack to ensure that the original axes tick labels are on top of whatever is plotted in the twinned axes" didn't work for me so as an alternative I've used:
from matplotlib.ticker import MaxNLocator
#Match the tick point locations by setting the same number of ticks in the
# 2nd axis as the first
ax2.yaxis.set_major_locator(MaxNLocator(nbins=len(ax1.get_yticks())))
#Set the last tick as the plot limit
ax2.set_ylim(0, ax2.get_yticks()[-1])
#Remove the tick label at zero
ax2.yaxis.get_major_ticks()[0].label1.set_visible(False)