I'm trying to make a three-dimensional plot, but I can't create the 3D Axes.
When I try, it gives me the an error stating "ValueError: Unknown projection '3d'".
Here's how I've tried to create the Axes object
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
plt.show()
How do I create a 3D Axes object in matplotlib?
In order to create a 3D Axes, you need to import the mplot3d toolkit:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
plt.show()
There are several 3D examples in the gallery:
http://matplotlib.org/examples/mplot3d
From the Matplotlib documentation, "Valid values for projection are: [‘aitoff’, ‘hammer’, ‘lambert’, ‘mollweide’, ‘polar’, ‘rectilinear’]".
You are providing an invalid keyword argument to the add_subplot() method. It looks like you are trying to create a 3D plot in Cartesian coordinates. The projection keyword is not needed to make such a plot.
Related
I am trying something like this:
import xarray as xr
import numpy as np
(lon,lat)=np.meshgrid(np.arange(0,6,1),np.arange(0,6,1))
da_data=xr.DataArray(data=np.random.randn(6,6),dims=['y','x'],
coords=dict(LAT=(['y','x'],lat), LON=(['y','x'],lon)) )
da_data.plot.contour(kwargs=dict(inline=True))
I can see the contours but no labels. What am I doing wrong?
xarray.plot uses matplotlib as a backend, and you can replace your last line with the following, using matplotlib's Axis.clabel
fig, ax = plt.subplots()
CS = da_data.plot.contour(kwargs=dict(inline=True), ax=ax)
ax.clabel(CS)
See the matplotlib.contour.ContourLabeler.clabel documentation and the countour label demo for more info.
I am creating shot plots for NHL games and I have succeeded in making the plot, but I would like to draw the lines that you see on a hockey rink on it. I basically just want to draw two circles and two lines on the plot like this.
Let me know if this is possible/how I could do it
Pandas plot is in fact matplotlib plot, you can assign it to variable and modify it according to your needs ( add horizontal and vertical lines or shapes, text, etc)
# plot your data, but instead diplaying it assing Figure and Axis to variables
fig, ax = df.plot()
ax.vlines(x, ymin, ymax, colors='k', linestyles='solid') # adjust to your needs
plt.show()
working code sample
import pandas as pd
import matplotlib.pyplot as plt
import seaborn
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection
df = seaborn.load_dataset('tips')
ax = df.plot.scatter(x='total_bill', y='tip')
ax.vlines(x=40, ymin=0, ymax=20, colors='red')
patches = [Circle((50,10), radius=3)]
collection = PatchCollection(patches, alpha=0.4)
ax.add_collection(collection)
plt.show()
I am trying to plot multiple rgb images with matplotlib
the code I am using is:
import numpy as np
import matplotlib.pyplot as plt
for i in range(0, images):
test = np.random.rand(1080, 720,3)
plt.subplot(images,2,i+1)
plt.imshow(test, interpolation='none')
the subplots appear tiny though as thumbnails
How can I make them bigger?
I have seen solutions using
fig, ax = plt.subplots()
syntax before but not with plt.subplot ?
plt.subplots initiates a subplot grid, while plt.subplot adds a subplot. So the difference is whether you want to initiate you plot right away or fill it over time. Since it seems, that you know how many images to plot beforehand, I would also recommend going with subplots.
Also notice, that the way you use plt.subplot you generate empy subplots in between the ones you are actually using, which is another reason they are so small.
import numpy as np
import matplotlib.pyplot as plt
images = 4
fig, axes = plt.subplots(images, 1, # Puts subplots in the axes variable
figsize=(4, 10), # Use figsize to set the size of the whole plot
dpi=200, # Further refine size with dpi setting
tight_layout=True) # Makes enough room between plots for labels
for i, ax in enumerate(axes):
y = np.random.randn(512, 512)
ax.imshow(y)
ax.set_title(str(i), fontweight='bold')
I want to create a 3d plot like the following, such that axes pass through the origin with ticks on them.
PS: I could do that for 2D plots using matplotlib (the following figure). I searched a lot to do the same for 3D plots but I did not find any info.
If you want to restrict yourself to just matplotlib then we can use quiver3d plot as shown below. But the results may not be very visually appealing. You can see here how to add 3D text annotations.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.set_xlim(0,2)
ax.set_ylim(0,2)
ax.set_zlim(0,2)
ax.view_init(elev=20., azim=32)
# Make a 3D quiver plot
x, y, z = np.zeros((3,3))
u, v, w = np.array([[1,1,0],[1,0,1],[0,1,1]])
ax.quiver(x,y,z,u,v,w,arrow_length_ratio=0.1)
plt.show()
So I'm trying to create a figure that presents a 3d plot from data points, along with the plots 3 projections in 3 other subplots. I can add the subplots for the projections with no problems, but when I try to place the 3 dimensional plot into the figure things backfire.
here's my code:
def plotAll(data):
fig = plt.figure()
plot_3d = fig.add_subplot(221)
ax = Axes3D(plot_3d)
for i,traj in enumerate(data.values()):
ax.plot3D([traj[0][-1]],[traj[1][-1]],[traj[2][-1]],".",color=[0.91,0.39,0.046])
#plot_12v13 = fig.add_subplot(222)
#plot_projections(data,0,1)
#plot_13v14 = fig.add_subplot(223)
#plot_projections(data,1,2)
#plot_12v14 = fig.add_subplot(224)
#plot_projections(data,0,2)
#plt.plot()
which throws back:
'AxesSubplot' object has no attribute 'transFigure'
I'm using matplotlib 0.99.3, any help would be greatly appreciated, thanks!
I was searching for a way to create my 3D-plots with the nice fig, axes = plt.subplots(...) shortcut, but since I just browsed Matplotlib's mplot3d tutorial, I want to share a quote from the top of this site.
New in version 1.0.0: This approach is the preferred method of creating a 3D axes.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
Note
Prior to version 1.0.0, the method of creating a 3D axes was different. For those using older versions of matplotlib, change ax = fig.add_subplot(111, projection='3d') to ax = Axes3D(fig).
So if you have to use the <1.0.0 version of Matplotlib, this should be taken into account.
If you would like to use plt.subplots instead of plt.subplot (see the difference here), then you can do something like this one:
import matplotlib.pyplot as plt
from matplotlib import cm # for a scatter plot
from mpl_toolkits.mplot3d import Axes3D
fig, ax = plt.subplots(1,2,figsize=(10,10),subplot_kw=dict(projection='3d'))
sc1 = ax[0].scatter(x,y,z, c = true, cmap=cm.jet)
ax[0].set_title('True solution')
sc2 = ax[1].scatter(x,y,z c = y_pred, cmap=cm.jet)
ax[1].set_title('Predicted Solution')
Well, I don't know how to set individual axes as 3D using plt.subplots. It would be helpful if someone could comment down.
The preferred way of creating an 3D axis is giving the projection keyword:
def plotAll(data):
fig = plt.figure()
ax = fig.add_subplot(221, projection='3d')
for i,traj in enumerate(data.values()):
ax.plot3D([traj[0][-1]],[traj[1][-1]],[traj[2][-1]],".",color=[0.91,0.39,0.046])
plot_12v13 = fig.add_subplot(222)
plot_projections(data,0,1)
plot_13v14 = fig.add_subplot(223)
plot_projections(data,1,2)
plot_12v14 = fig.add_subplot(224)
plot_projections(data,0,2)
plt.plot()
Unfortunately, you didn't supply a working example with suitable data, so I couldn't test the code. Also, I would recommend updating to a newer version of matplotlib.