Python : How to plot 3d graphs using Python? - python

I am using matplotlib for doing this
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
x = [6,3,6,9,12,24]
y = [3,5,78,12,23,56]
ax.plot(x, y, zs=0, zdir='z', label='zs=0, zdir=z')
plt.show()
Now this builds a graph that is horizontal in the 3d space. How do I make the graph vertical so that it faces the user?
What I want to do is build multiple such vertical graphs that are separated by some distance and are facing the user.

bp's answer might work fine, but there's a much simpler way.
Your current graph is 'flat' on the z-axis, which is why it's horizontal. You want it to be vertical, which means that you want it to be 'flat' on the y-axis. This involves the tiniest modification to your code:
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
x = [6,3,6,9,12,24]
y = [3,5,78,12,23,56]
# put 0s on the y-axis, and put the y axis on the z-axis
ax.plot(xs=x, ys=[0]*len(x), zs=y, zdir='z', label='ys=0, zdir=z')
plt.show()
Then you can easily have multiple such graphs by using different values for the ys parameter (for example, ys=[2]*len(x) instead would put the graph slightly behind).

Mayavi, in particular the mlab module, provides powerful 3D plotting that will work on large and or complex data, and should be easy to use on numpy arrays.

You can set the view angle of the 3d plot with the view_init() function. The example below is for version 1.1 of matplotlib.
from mpl_toolkits.mplot3d import axes3d
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = [6,3,6,9,12,24]
y = [3,5,78,12,23,56]
ax.plot(x, y, zs=0, zdir='z', label='zs=0, zdir=z')
ax.view_init(90, -90)
plt.show()

According to the documentation you want to use the ax.plot_surface(x,y,z) method. More information and chart types here.
The following should work:
x = [1,2,3]
y = [4,5,6]
z = [7,8,9]
data = zip(x,y,z)
#map data on the plane
X, Y = numpy.meshgrid(arange(0, max(x), 1), arange(0, max(y), 1))
Z = numpy.zeros((len(Y), len(X)), 'Float32')
for x_,y_,z_ in data:
Z[x_, y_] = z_ #this should work, but only because x and y are integers
#and arange was done with a step of 1, starting from 0
fig = p.figure()
ax = p3.Axes3D(fig)
ax.plot_surface(X, Y, Z)

Related

Way of plotting data into boxes instead of pyramids using mplot3d

So I have an array of values that I am trying to plot using the plot_surface command. Specifically I have a 30x30 array with one in the middle and zeros elsewhere. When I plot it this is what I obtain:
I would like however for the value to be represented as a cuboid. Is that possible?
Thank you
edit: Code that shows the figure
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
N=30
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(0, N)
z = np.zeros((N,N))
z[15,15] = 1
X, Y = np.meshgrid(x, y)
ax.plot_surface(X, Y, z, cmap='YlOrBr')
plt.show(block=False)
I think a 3D bar plot will give what you're looking for.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
N=30
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(0, N)
z_bottom = np.zeros((N,N))
z_top = z_bottom.copy()
z_top[15,15] = 1
X, Y = np.meshgrid(x, y)
ax.bar3d(X.ravel(), Y.ravel(), z_bottom.ravel(), 1, 1, z_top.ravel())
plt.show(block=False)
The full documentation is here if you want to play with the colors and so forth.

How to make a 3D data surface plot using matplotlib in python

I am trying to make a 3d surface plot of experimental data using matplotlib. I would like to plot different Z values against the same X and Y axes. When I try the simple code below, I get the error
"plot_surface() missing 1 required positional argument: 'Z' ".
It seems that the Axes3D package only work if Z is given as a function of X and Y, rather than an actual data matrix. Does anybody know a way around this?
Please note that the Zmatrix that I need is actual data, but I just used a random matrix for illustration here.
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
X=[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
Y= [0,2500,5000,7500,10000,15000,20000,25000,30000,35000,40000,45000,50000,55000,60000,65000,70000]
Zmatrix=np.random.rand(len(X),len(Y))
Axes3D.plot_surface(X,Y,Zmatrix)
There were sone issues with your code:
First you have to get a meshgrid of X and Y (all combinations as matrices). Next swap len(X) and len(Y) inside the Zmatrix. And first define ax = Axes3D(plt.gcf()) and plot_surface afterwards on ax.
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
X=[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
Y= [0,2500,5000,7500,10000,15000,20000,25000,30000,35000,40000,45000,50000,55000,60000,65000,70000]
Xm, Ym = np.meshgrid(X, Y)
Zmatrix=np.random.rand(len(Y),len(X))
ax = Axes3D(plt.gcf())
ax.plot_surface(Xm, Ym, Zmatrix)
Here is an example of surface plot.
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import random
def fun(x, y):
return x**2 + y
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-3.0, 3.0, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)
ax.plot_surface(X, Y, Z)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()

Python: How to plot these 3d lines as an isosurface?

I have some x, y, z data for which I can plot multiple 3d lines/traces into order to build the following image:
The python code building this is like so:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=[20, 20])
ax = fig.add_subplot(111, projection='3d')
midpoint = len(t)/2 - 10000
for i in range(100):
x = xs_array[i]
y = ys_array[i]
ax.plot(t[midpoint:midpoint+20000], x[midpoint:midpoint+20000], y[midpoint:midpoint+20000], alpha=0.4)
I want to build a isosurface like the one shown below as it is hard to interpret the shape in the current form, how might I go about that?

Matplotlib: Plot 2d array radially to make 3d Scatterplot

I am looking to make a plot similar to the one found here, with the simple difference that I would like to to set the distance from the center for each point. Ie, given a slice of the plot is a circle, where I would like each of the points to be at a definable distance from the center.
What I a starting with, given a simple modification of the previously mentioned answer:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
import numpy as np
from scipy.interpolate import interp1d
from matplotlib import cm
from matplotlib import pyplot as plt
step = 0.04
maxval = 1.0
fig = plt.figure()
ax = Axes3D(fig)
# u here would define the desired distance from radial axis
# u=np.array([0,1,2,1,0,2,4,6,4,2,1])
v=np.array([4,4,6,3,6,4,1,4,4,4,4])
r=np.array([0,1,2,3,4,5,6,7,8,9,10])
f=interp1d(r,u)
# walk along the circle
p = np.linspace(0,2*np.pi,len(r))
R,P = np.meshgrid(r,p)
# transform them to cartesian system
X,Y = R*np.cos(P),R*np.sin(P)
Z=f(R)
ax.scatter(X, Y, Z)#, rstride=1, cstride=1, cmap=cm.jet)
ax.set_xticks([])
fig.savefig(str(output_prefix + '3d..png'), dpi=(200))
What I would like to plot (apologies for the blurred sketch):
I have tried using interp2d to add the u variable commented out above, but no luck. Changing Z to the array u threw the error that X, Y, and Z must be the same size ("Argument 'zs' must be of same size as 'xs' ", understandably as X and Y are now interpolated) What do I need to do? Any tips would be appreciated!
I don't know exactly what you meant in your question.
I made v to be the offset of the center of the circles in x-axis.
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from scipy.interpolate import interp1d
from matplotlib import pyplot as plt
step = 0.04
maxval = 1.0
fig = plt.figure()
ax = Axes3D(fig)
# v here would define the desired distance from radial axis
u=np.array([0,1,2,1,0,2,4,6,4,2,1])
v=np.array([4,4,6,3,6,4,1,4,4,4,4])
r=np.array([0,1,2,3,4,5,6,7,8,9,10])
f=interp1d(r,u)
# walk along the circle
V = np.tile(v, (len(u), 1))
p = np.linspace(0,2*np.pi,len(r))
R,P = np.meshgrid(r,p)
# transform them to cartesian system
X,Y = V + R*np.cos(P),R*np.sin(P)
Z=f(R)
ax.scatter(X, Y, Z)#, rstride=1, cstride=1, cmap=cm.jet)
ax.set_xticks([])
plt.show()

How to plot contourf and my graph in the same figure

I have a figure showing the contourf plot and another showing a plot i've made earlier and I want to plot both on the same figure what should I do?
Here is the code of my contourf plot:
import pylab as pl
from pylab import *
import xlrd
import math
import itertools
from matplotlib import collections as mc
import matplotlib.pyplot as plt
import copy as dc
import pyexcel
from pyexcel.ext import xlsx
import decimal
x_list = linspace(0, 99, 100)
y_list = linspace(0, 99, 100)
X, Y = meshgrid(x_list, y_list, indexing='xy')
Z = [[0 for x in range(len(x_list))] for x in range(len(y_list))]
for each_axes in range(len(Z)):
for each_point in range(len(Z[each_axes])):
Z[len(Z)-1-each_axes][each_point] = power_at_each_point(each_point, each_axes)
figure()
CP2 = contourf(X, Y, Z, cmap=plt.get_cmap('Reds'))
colorbar(CP2)
title('Coverage Plot')
xlabel('x (m)')
ylabel('y (m)')
show()
This is the code of my previously plotted plot:
lc = mc.LineCollection(lines, linewidths=3)
fig, ax = pl.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.05)
#The code blow is just for drawing the final plot of the building.
Nodes = xlrd.open_workbook(Node_file_location)
sheet = Nodes.sheet_by_index(0)
Node_Order_Counter = range(1, sheet.nrows + 1)
In_Node_Order_Counter = 0
for counter in range(len(Node_Positions_Ascending)):
plt.plot(Node_Positions_Ascending[counter][0], Node_Positions_Ascending[counter][1], marker='o', color='r',
markersize=6)
pl.text(Node_Positions_Ascending[counter][0], Node_Positions_Ascending[counter][1],
str(Node_Order_Counter[In_Node_Order_Counter]),
color="black", fontsize=15)
In_Node_Order_Counter += 1
#Plotting the different node positions on our plot & numbering them
pl.show()
Without your data we can't see what the plot is supposed to look like, but I have some general recommendations.
Don't use pylab. And if you absolutely must use it, use it within its namespace, and don't do from pylab import *. It makes for very sloppy code - for example, linspace and meshgrid are actually from numpy, but it's hard to tell that when you use pylab.
For complicated plotting, don't even use pyplot. Instead, use the direct object plotting interface. For example, to make a normal plot on top of a contour plot, (such as you want to do) you could do the following:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = np.linspace(1, 5, 20)
y = np.linspace(2, 5, 20)
z = x[:,np.newaxis] * (y[np.newaxis,:])**2
xx, yy = np.meshgrid(x, y)
ax.contourf(xx, yy, z, cmap='Reds')
ax.plot(x, 0.2*y**2)
plt.show()
Notice that I only used pyplot to create the figure and axes, and show them. The actual plotting is done using the AxesSubplot object.

Categories

Resources