Plotting Poly3DCollection using add_collection3d - matplotlib

I have tree arrays of the same size representing the spherical coordinates of points in space. I want to plot them transformed in cartesian coordinates. I am trying to produce a surface and I need to use the add_collection3d method instead of the plot_surface because of the dimensions of my arrays. The original arrays have different lengths in spherical coordinates and the transformation into cartesian is not linear.
A simplified example follows:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LightSource
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from mpl_toolkits.mplot3d import Axes3D
phi_rad = np.linspace(0,360, 10)/180.0*np.pi
theta_rad = np.linspace(0,360, 10)/180.0*np.pi # cos(theta)
counts_str = np.linspace(0, 100, 10) # counts
# convertion to cartesian coordinates 1D arrays
x = counts_str * np.sin(theta_rad) * np.cos(phi_rad)
y = counts_str * np.sin(theta_rad) * np.sin(phi_rad)
z_str = counts_str * np.cos(theta_rad)
verts = [list(zip(x, y, z_str))]
fig = plt.figure()
ax = Axes3D(fig)
ax.add_collection3d(Poly3DCollection(verts, cmap="hot", alpha=0.9))
ls = LightSource(azdeg=225.0, altdeg=45.0)
ax.set_xlim3d(x.min(), x.max())
ax.set_ylim3d(y.min(), y.max())
ax.set_zlim3d(z_str.min(), z_str.max())
plt.show()
I would like to apply a cmap and a LightSource (don't affect the plot), as well as an antialiased because in my real data z is an array with 20000 elements.
Looking forward to hearing from your collective intelligence!

Solution: reshape all the three vectors and use surface plot!
Creating a 3D surface plot from three 1D arrays

Related

Fitting & scaling a probability density function correctly to a histogram with a logarithmic x-axis?

I am trying to fit a gilbrat PDF to a dataset (that I have in form of a list). I want to show the data in a histogram with a logarithmic x-scale and add the fitted curve. However, the curve seems too flat compared to the histogram, like in this picture: I tried to scale the pdf according to Fitting a Gaussian to a histogram with MatPlotLib and Numpy - wrong Y-scaling? , but the problem remains.
Here is a code example with randomly created data:
import scipy.stats as st
import numpy as np
import matplotlib.pyplot as plt
#create random dataset
data = st.gilbrat.rvs(scale = 10, size = 100).tolist()
param = st.gilbrat.fit(data)
x = np.linspace(min(data),max(data),len(data))
pdf = st.gilbrat.pdf(x, param[0], param[1])
plt.figure()
logbins = np.logspace(np.log10(np.min(data)),np.log10(np.max(data)),20)
result = plt.hist(data, bins=logbins, edgecolor="black", alpha = 0.5, label="data")
dx = result[1][1] - result[1][0]
plt.plot(x,pdf * (len(data)*dx), label="fit")
plt.xscale('log')
plt.xlabel("x")
plt.ylabel("Number of occurence")
plt.legend()
Am I missing something?
As your bins aren't equally spaced, the histogram isn't similar to a scaled version of the pdf. The bins at the right represent a much wider x-range than the ones at the left.
To predict the heights of the rectangles given the pdf, each bin region needs a different scaling factor, depending on the width of that bin.
The following code rescales each region independently, resulting in a discontinuously scaled pdf.
import scipy.stats as st
import numpy as np
import matplotlib.pyplot as plt
# create random dataset
np.random.seed(1)
data = st.gilbrat.rvs(scale=10, size=100)
param = st.gilbrat.fit(data)
x = np.logspace(np.log10(data.min()), np.log10(data.max()), 500)
pdf = st.gilbrat.pdf(x, param[0], param[1])
plt.figure()
logbins = np.logspace(np.log10(data.min()), np.log10(data.max()), 20)
heights, bins, rectangles = plt.hist(data, bins=logbins, edgecolor="black", alpha=0.5, label="data")
for b0, b1 in zip(bins[:-1], bins[1:]):
dx = b1 - b0
x_bin = np.logspace(np.log10(b0), np.log10(b1), 100)
pdf_bin = st.gilbrat.pdf(x_bin, param[0], param[1])
plt.plot(x_bin, pdf_bin * (len(data) * dx), color='crimson',
label="expected bin height" if b0 == bins[0] else None)
plt.xscale('log')
plt.xlabel("x")
plt.ylabel("Number of occurence")
plt.legend()
plt.tight_layout()
plt.show()
Here is another take, smoothing out the scaling of the pdf to any log-scale histogram. The dx is different at each x-position, in contrast to the histogram with linearly spaced bins.
import scipy.stats as st
import numpy as np
import matplotlib.pyplot as plt
# create random dataset
np.random.seed(1)
data = st.gilbrat.rvs(scale=10, size=100)
param = st.gilbrat.fit(data)
x = np.logspace(np.log10(data.min()), np.log10(data.max()), 500)
pdf = st.gilbrat.pdf(x, param[0], param[1])
plt.figure()
logbins = np.logspace(np.log10(data.min()), np.log10(data.max()), 20)
heights, bins, rectangles = plt.hist(data, bins=logbins, edgecolor="black", alpha=0.5, label="data")
dx_array = np.logspace(np.log10(bins[1] - bins[0]), np.log10(bins[-1] - bins[-2]), len(x))
plt.plot(x, pdf * len(data) * dx_array, color='crimson', label="pdf rescaled like histogram")
plt.xscale('log')
plt.xlabel("x")
plt.ylabel("Number of occurence")
plt.legend()
plt.tight_layout()
plt.show()

Interpolation between two values using python

I am trying to perform a linear interpolation in Python from a graph which have coordinate values say (x1,y1) and (x2,y2). According to my values I will get a straight line in the graph as in this figure
My aim is at 10^6(x-axis value) should give me the value of the parameter on y-axis but presently i am getting the extrapolate value not on the line.
Required Output:OUtput needed
I tried with below Code
import matplotlib.pyplot as plt
import math
import numpy as np
x = np.array([1, 10000000])
y = np.array([0.65, 0.25])
BK = np.asarray(np.interp(0.7,x,y))
print("aa:",BK)
plt.xscale("log")
plt.plot(x,y)
plt.plot(1000000,BK, marker="o",markersize=10)
plt.plot([1000000,1000000,0],[0,BK,BK], "b--", linewidth=1)
plt.xlim(1, 100000000)
plt.ylim(0, 1)
plt.show()
Note that the line drawn in the chart is completely unrelated to the data because it is a line in the chart, not in data coordinates. An interpolation of that line hence has zero meaning!
If you still want to interpolate that line you first need to transform to logspace:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1, 10000000])
y = np.array([0.65, 0.25])
xinp = 1e6
BK = np.asarray(np.interp(np.log(xinp), np.log(x), y))
print("aa:",BK)
plt.xscale("log")
plt.plot(x,y)
plt.plot(xinp, BK, marker="o",markersize=10)
plt.plot([1000000,1000000,0],[0,BK,BK], "b--", linewidth=1)
plt.xlim(1, 100000000)
plt.ylim(0, 1)
plt.show()

Polar Plot in Python - Repeat of peak looks like kaleidoscope

I'm trying to plot a polar plot in matplotlib. When I use normal, rectangular coordinates, I get the plot I want:
dir_mesh, f_mesh = np.meshgrid(dir,freq[indsf])
pl.pcolor(dir_mesh,f_mesh,S1)
correct plot
If I use a polar projection, multiple peaks are present!
ax = pl.subplot(111,projection = "polar")
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
c = ax.pcolor(dir_mesh,f_mesh,S1)
kaleidoscope polar plot (wrong)
The units of a polar plot are radiants. If you supply your data in degrees, ranging from 0 to 360, the data will revolve 57 times around the polar plot and the result will look something like this:
import matplotlib.pyplot as plt
import numpy as np
theta = np.arange(0,361,10)
r = np.linspace(0.,0.8,len(theta) )
ax = plt.subplot(111,projection = "polar")
ax.plot(theta,r)
plt.show()
In order to get the desired result you need to scale your theta data to the range between 0 and 2π.
e.g. theta = theta/180.*np.pi.
import matplotlib.pyplot as plt
import numpy as np
theta = np.arange(0,361,10)
theta = theta/180.*np.pi
r = np.linspace(0.,0.8,len(theta) )
ax = plt.subplot(111,projection = "polar")
ax.plot(theta,r)
plt.show()

How can I plot function values on a sphere?

I have a Nx2 matrix of lat lon coordinate pairs, spatial_data, and I have an array of measurements at these coordinates.
I would like to plot this data on a globe, and I understand that Basemap can do this. I found this link which shows how to plot data if you have cartesian coordinates. Does there exist functionality to convert lat,lon to cartesian coordinates? Alternatively, is there a way to plot this data with only the lat,lon information?
You can use cartopy:
import numpy as np
import matplotlib.pyplot as plt
from cartopy import crs
# a grid for the longitudes and latitudes
lats = np.linspace(-90, 90, 50)
longs = np.linspace(-180, 180, 50)
lats, longs = np.meshgrid(lats, longs)
# some data
data = lats[1:] ** 2 + longs[1:] ** 2
fig = plt.figure()
# create a new axes with a cartopy.crs projection instance
ax = fig.add_subplot(1, 1, 1, projection=crs.Mollweide())
# plot the date
ax.pcolormesh(
longs, lats, data,
cmap='hot',
transform=crs.PlateCarree(), # this means that x, y are given as longitude and latitude in degrees
)
fig.tight_layout()
fig.savefig('cartopy.png', dpi=300)
Result:

Plotting masked numpy array leads to incorrect colorbar

I'm trying to create a custom color bar for a matplotlib PolyCollection. Everything seems ok until I attempt to plot a masked array. The color bar no longer shows the correct colors even though the plot does. Is there a different procedure for plotting masked arrays?
I'm using matplotlib 1.4.0 and numpy 1.8.
Here's my plotting code:
import numpy
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
vertices = numpy.load('vertices.npy')
array = numpy.load('array.npy')
# Take 2d slice out of 3D array
slice_ = array[:, :, 0:1].flatten(order='F')
fig, ax = plt.subplots()
poly = PolyCollection(vertices, array=slice_, edgecolors='black', linewidth=.25)
cm = mpl.colors.ListedColormap([(1.0, 0.0, 0.0), (.2, .5, .2)])
poly.set_cmap(cm)
bounds = [.1, .4, .6]
norm = mpl.colors.BoundaryNorm(bounds, cm.N)
fig.colorbar(poly, ax=ax, orientation='vertical', boundaries=bounds, norm=norm)
ax.add_collection(poly, autolim=True)
ax.autoscale_view()
plt.show()
Here's what the plot looks like:
However, when I plot a masked array with the following change before the slicing:
array = numpy.ma.array(array, mask=array > .5)
I get a color bar that now shows only a single color. Even though both colors are (correctly) still shown in the plot.
Is there some trick to keeping a colobar consistent when plotting a masked array? I know I can use cm.set_bad to change the color of masked values, but that's not quite what I'm looking for. I want the color bar to show up the same between these two plots since both colors and the color bar itself should remain unchanged.
Pass the BoundaryNorm to the PolyCollection, poly. Otherwise, poly.norm gets set to a matplotlib.colors.Normalize instance by default:
In [119]: poly.norm
Out[119]: <matplotlib.colors.Normalize at 0x7faac4dc8210>
I have not stepped through the source code sufficiently to explain exactly what is happening in the code you posted, but I speculate that the interaction of this Normalize instance and the BoundaryNorm make the range of values seen by the fig.colorbar different than what you expected.
In any case, if you pass norm=norm to PolyCollection, then the result looks correct:
import numpy
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.collections as mcoll
import matplotlib.colors as mcolors
numpy.random.seed(4)
N, M = 3, 3
vertices = numpy.random.random((N, M, 2))
array = numpy.random.random((1, N, 2))
# vertices = numpy.load('vertices.npy')
# array = numpy.load('array.npy')
array = numpy.ma.array(array, mask=array > .5)
# Take 2d slice out of 3D array
slice_ = array[:, :, 0:1].flatten(order='F')
fig, ax = plt.subplots()
bounds = [.1, .4, .6]
cm = mpl.colors.ListedColormap([(1.0, 0.0, 0.0), (.2, .5, .2)])
norm = mpl.colors.BoundaryNorm(bounds, cm.N)
poly = mcoll.PolyCollection(
vertices,
array=slice_,
edgecolors='black', linewidth=.25, norm=norm)
poly.set_cmap(cm)
fig.colorbar(poly, ax=ax, orientation='vertical')
ax.add_collection(poly, autolim=True)
ax.autoscale_view()
plt.show()