3D scatter_plot across 3D surface_plot - python

With the following code I try to plot a single scatter point over a 3D surface plot. But it is not working. Have tried Axes3D.text(x, y, z, s, zdir=None, **kwargs) instead of Axes3D.scatter(xs, ys, zs=0, zdir='z', s=20, c=None, depthshade=True,*args, **kwargs) which works. So I am curious why scatter is not working. What am I doing wrong?
Code
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib import cm
from pylab import figure
from mpl_toolkits.mplot3d import Axes3D
fig = figure(figsize=(30,30))
ax = Axes3D(fig)
x=160+np.linspace(-100,100,100)
y=245+np.linspace(-100,100,100)
X,Y=np.meshgrid(x.round(0),y.round(0))
print(threshold1)
Z=Y-X
ax.plot_surface(X,Y,Z,cmap=cm.coolwarm,linewidth=3)
ax.scatter(160,245,85,s=400,c="b")
ax.tick_params(labelsize=35,direction='out', length=6, width=2)
plt.show()
Figure

Related

3D scatter with two axes in logscale

I am trying to get a scatter plot with 2 axes (x,z) in a log scale using set_scale but that doesn't work.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
x=np.linspace(0,500,10)
y=np.linspace(0,1,10)
z=np.linspace(0,100000,10)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot(x, y, z,'o', c='g')
ax.grid()
#ax.set_xscale('log')
#ax.set_zscale('log')
#ax.set_xlim([min(x), max(x)])
#ax.set_zlim([min(z), max(z)])
plt.show()

3D plotting in Python - Adding a Legend to Scatterplot

from mpl_toolkits.mplot3d import Axes3D
ax.scatter(X_lda[:,0], X_lda[:,1], X_lda[:,2], alpha=0.4, c=y_train, cmap='rainbow', s=20)
plt.legend()
plt.show()
Essentially I'd like to add a legend for the scatterplot that shows the unique values in y_train and what color point it corresponds to on the plot.
The output plot:
Producing either a legend or a colorbar for a scatter is usually quite simple:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x,y,z = (np.random.normal(size=(300,4))+np.array([0,2,4,6])).reshape(3,400)
c = np.tile([1,2,3,4], 100)
fig, ax = plt.subplots(subplot_kw=dict(projection="3d"))
sc = ax.scatter(x,y,z, alpha=0.4, c=c, cmap='rainbow', s=20)
plt.legend(*sc.legend_elements())
plt.colorbar(sc)
plt.show()

Using seaborn and contourf, how can I plot gridlines?

Using the following code, the first contour plot has grid lines. For the second plot, I have imported seaborn, but the grid lines don't show up. What do I need to add to make the grid lines show on the second plot.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
dx=0.05
x=np.arange(0,5+dx,dx)
y=x
X,Y = np.meshgrid(x,y)
Z = np.sin(X)**10+np.cos(10+Y*Y)*np.cos(X)
nbins=10
levels=mpl.ticker.MaxNLocator(nbins=nbins).tick_values(Z.min(),Z.max())
plt.figure()
plt.contourf(x,y,Z,levels=levels)
plt.colorbar()
plt.grid('on')
import seaborn as sns
sns.set_context("notebook")
sns.set_style("whitegrid")
plt.figure()
plt.contourf(x,y,Z,levels=levels)
plt.colorbar()
plt.grid('on')
plt.show()
You either need to change either the axes.axisbelow rc parameter or the zorder of the contourf plot. So you could do
sns.set(context="notebook", style="whitegrid",
rc={"axes.axisbelow": False})
When you set up the style or
plt.contourf(x, y, Z, levels=levels, zorder=0)
When you draw the plot.

Adding different shades to a 3D plot in Python and Matplotlib

I'm looking for a VERY simple way of changing the colour of my 3D plot to make it look more interesting.
Here is my code (had to delete most of it because said i had too much code in my post):
from numpy import *
from matplotlib.pyplot import *
from mpl_toolkits.mplot3d import Axes3D
from numpy import array
from matplotlib import pyplot
from math import sqrt
X, Y = np.mgrid[:9, :21]
fig = figure()
ax = fig.add_subplot(1,1,1, projection='3d')
ax.set_xlabel('Time')
ax.set_ylabel('Step')
ax.set_zlabel('Probability')
ax.plot_surface(X, Y, probs)
show()
Here is my graph:
Any help would really be appreciated!!
Ive tried using the http://matplotlib.org/mpl_toolkits/mplot3d to no avail

matplotlib 3D ribbon plot

I'm using NumPy 1.6.2, SciPy 0.11.0, Matplotlib 1.1.1. Can I plot ribbons as in the picture?
This is the full code.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata
from mpl_toolkits.mplot3d import Axes3D
data=np.genfromtxt('fluorescence_2.txt')
x=data[:,0]
fig=plt.figure()
ax=fig.gca(projection='3d')
for i in range(1,17,2):
y=data[:,i]
z=data[:,i+1]
xi=np.linspace(min(x),max(x))
yi=np.linspace(min(y),max(y))
X,Y=np.meshgrid(xi,yi)
Z=griddata(x,y,z,xi,yi)
ax.plot_surface(X,Y,Z,rstride=50,cstride=1,cmap='RdYlBu')
ax.set_zlim3d(np.min(Z),np.max(Z))
ax.set_title('Fluorescence spectra (WL ex = 350 nm)')
ax.set_xlabel('WL em (nm)')
ax.set_ylabel('Spectrum')
ax.set_yticks([])
ax.set_zlabel('Emission')
plt.show()
In my previous version was necessary to change the data table structure before the load into the script. The following version is my last and it plots the ribbons directly from the original data, a simple table of absorbances.
import itertools
import numpy as np
from matplotlib.mlab import griddata
from mpl_toolkits.mplot3d import Axes3D
from pylab import *
matplotlib.rcParams.update({'font.size':10})
spectra=loadtxt('C:/.../absorbance.txt')
fig=figure()
ax=fig.gca(projection='3d')
for i in range(0,7+1):
y=spectra[:,i]
x=sorted(range(1,len(y)+1)*2)
a=[i,i+1]*len(y)
b=list(itertools.chain(*zip(y,y)))
xi=np.linspace(min(x),max(x))
yi=np.linspace(min(a),max(a))
X,Y=np.meshgrid(xi,yi)
Z=griddata(x,a,b,xi,yi)
ax.plot_surface(X,Y,Z,rstride=50,cstride=1,cmap='Spectral')
ax.set_zlim3d(np.min(Z),np.max(Z))
ax.grid(False)
ax.w_xaxis.pane.set_visible(False)
ax.w_yaxis.pane.set_visible(False)
ax.w_zaxis.pane.set_color('gainsboro')
ax.set_title('Molecular spectra')
ax.set_xlim3d(0,23)
ax.set_xticks([1.6735,6.8367,12.0000,17.1633,22.3265])
ax.set_xticklabels(['350','400','450','500','550'])
ax.set_xlabel('Wavelength (nm)')
ax.set_yticks([0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5])
ax.set_yticklabels(['1','2','3','4','5','6','7','8'])
ax.set_ylabel('Spectrum')
ax.set_zlim3d(0,2)
ax.set_zlabel('Absorbance')
show()
Here is working code to create a ribbon plot. It is based off of the mplot3d example code: surface3d_demo.py and then modified to create ribbons. My code my not be the most efficient way to do it, but it works.
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
#create data
x = np.linspace(-10,5,200)
y = np.linspace(-5,5,40)
xGrid, yGrid = np.meshgrid(y, x)
z = np.sin(np.sqrt(xGrid**2 + yGrid**2))
numPts = x.shape[0]
numSets = y.shape[0]
fig = plt.figure()
ax = fig.gca(projection='3d')
#plot each "ribbon" as a surface plot with a certain width
ribbonWidth = 0.75
for i in np.arange(0,numSets-1):
X = np.vstack((x,x)).T
Y = np.ones((numPts,2))*i
Y[:,1] = Y[:,0]+ribbonWidth
Z = np.vstack((z[:,i],z[:,i])).T
surf = ax.plot_surface(X,Y,Z, rstride=1, cstride=1, cmap=cm.jet,
linewidth=0, vmin=-1, vmax=1)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
ax.set_xlabel('Data Points')
ax.set_ylabel('Data Set Number')
ax.set_ylim((0,numSets))
ax.set_zlabel('Z')
ax.set_zlim((-1, 1))
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()

Categories

Resources