Multiple stacked 3D contour plots in one figure in python [duplicate] - python

I just installed matplotlib and am trying to run one of there example scripts. However I run into the error detailed below. What am I doing wrong?
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, 16, extend3d=True)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()
The error is
Traceback (most recent call last):
File "<string>", line 245, in run_nodebug
File "<module1>", line 5, in <module>
File "C:\Python26\lib\site-packages\matplotlib\figure.py", line 945, in gca
return self.add_subplot(111, **kwargs)
File "C:\Python26\lib\site-packages\matplotlib\figure.py", line 677, in add_subplot
projection_class = get_projection_class(projection)
File "C:\Python26\lib\site-packages\matplotlib\projections\__init__.py", line 61, in get_projection_class
raise ValueError("Unknown projection '%s'" % projection)
ValueError: Unknown projection '3d'

First off, I think mplot3D worked a bit differently in matplotlib version 0.99 than it does in the current version of matplotlib.
Which version are you using? (Try running: python -c 'import matplotlib; print matplotlib."__version__")
I'm guessing you're running version 0.99, in which case you'll need to either use a slightly different syntax or update to a more recent version of matplotlib.
If you're running version 0.99, try doing this instead of using using the projection keyword argument:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D #<-- Note the capitalization!
fig = plt.figure()
ax = Axes3D(fig) #<-- Note the difference from your original code...
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, 16, extend3d=True)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()
This should work in matplotlib 1.0.x, as well, not just 0.99.

Just to add to Joe Kington's answer (not enough reputation for a comment) there is a good example of mixing 2d and 3d plots in the documentation at http://matplotlib.org/examples/mplot3d/mixed_subplots_demo.html which shows projection='3d' working in combination with the Axes3D import.
from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.add_subplot(2, 1, 1)
...
ax = fig.add_subplot(2, 1, 2, projection='3d')
In fact as long as the Axes3D import is present the line
from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.gca(projection='3d')
as used by the OP also works. (checked with matplotlib version 1.3.1)

Import mplot3d whole to use "projection = '3d'".
Insert the command below in top of your script. It should run fine.
from mpl_toolkits import mplot3d

I encounter the same problem, and #Joe Kington and #bvanlew's answer solve my problem.
but I should add more infomation when you use pycharm and enable auto import.
when you format the code, the code from mpl_toolkits.mplot3d import Axes3D will auto remove by pycharm.
so, my solution is
from mpl_toolkits.mplot3d import Axes3D
Axes3D = Axes3D # pycharm auto import
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
and it works well!

As recommended in other comments I found that importing "axes3d" resolved the issue:
from mpl_toolkits.mplot3d import Axes3D
It seems that this is needed if using an older version of matplotlib.pyplot

Try this:
import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.mplot3d import axes3d
fig=plt.figure(figsize=(16,12.5))
ax=fig.add_subplot(2,2,1,projection="3d")
a=ax.scatter(Dataframe['bedrooms'],Dataframe['bathrooms'],Dataframe['floors'])
plt.plot(a)

Related

Showing end point of the 3d line: Python 3D plot

I made a 3D plot using the following code in python. Here three arrays x, y and z are used for the plot. I want to show the last point of the arrays (or the end point of the 3D line) in the plot. I used the approach I would use in 2d plotting, i.e., I asked for plotting only the last points of each array using this command ax.plot(x[-1],y[-1],z[-1],'o'). But it doesn't work.
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
x=np.linspace(0,2*np.pi)
y=np.sin(x)
z=np.cos(x)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(x, y, z, lw=1)
ax.plot(x[-1],y[-1],z[-1],'o') # This line doesn't work
plt.show()
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
x=np.linspace(0,2*np.pi)
y=np.sin(x)
z=np.cos(x)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(x, y, z, lw=1)
ax.scatter(x[-1],y[-1],z[-1],'-') # This should do the job
plt.show()
Add Color and Label
ax.scatter(x[-1],y[-1],z[-1],'-',c="yellow",label="End Point")
plt.legend()
plt.show()
Additional explanation on why you were having an error:
You were telling python to draw you a ax.plot for 1 point. Which is impossible, because you cant draw a line using 1 point only. Therefore, you tell it to draw a scatter.

Matplotlib copy/duplicate a 3D figure?

I've tried to find a way to copy a 3D figure in matplotlib but I didn't find a solution which is appropriate in my case.
From these posts
How do I reuse plots in matplotlib?
and
How to combine several matplotlib figures into one figure?
Using fig2._axstack.add(fig2._make_key(ax),ax) as in the code below gives quite the good result but figure 2 is not interactive I can't rotate the figure etc :
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(1)
ax = fig.gca(projection = '3d')
ax.plot([0,1],[0,1],[0,1])
fig2 = plt.figure(2)
fig2._axstack.add(fig2._make_key(ax),ax)
plt.show()
An alternative would be to copy objects from ax to ax2 using a copy method proposed in this post How do I reuse plots in matplotlib? but executing the code below returns RuntimeError: Can not put single artist in more than one figure :
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np, copy
fig = plt.figure(1)
ax = fig.gca(projection = '3d')
ax.plot([0,1],[0,1],[0,1])
fig2 = plt.figure(2)
ax2 = fig2.gca(projection = '3d')
for n in range(len(ax.lines)) :
ax2.add_line(copy.copy(ax.lines[n]))
plt.show()
Those codes are pretty simple but I don't want to copy/paste part of my code for drawing similar figures
Thanks in advance for your reply !

how to fix Blank graphs when using figure module in PyDev?

I have a problem when making graphs using matplotlib,
for some simple graphs the library works fine, for example:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
but when I use figure module, i get blank figures, like this
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.linspace(0, 10, 200)
y = np.sin(x)
ax.plot(x, y, 'r-', linewidth=2, label=r'$y=\sin(x)$', alpha=0.6)
ax.legend(loc='upper center')
plt.show()
I've tried the same code in a a different python editor or using the shell and it woks fine. I'm using :
Windows,
PyDev v4.2,
python v2.7.10

The figure always has a line when I use basemap toolkit in python

The figure shows that there is one line across the America.
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
map = Basemap(projection='ortho',
lat_0=0, lon_0=0,resolution='l')
map.drawmapboundary(fill_color='aqua')
map.fillcontinents(color='coral',lake_color='aqua')
map.drawcoastlines()
x, y = map(0, 0)
map.plot(x, y, marker='D',color='m')
plt.show()

Matplotlib: "Unknown projection '3d'" error

I just installed matplotlib and am trying to run one of there example scripts. However I run into the error detailed below. What am I doing wrong?
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, 16, extend3d=True)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()
The error is
Traceback (most recent call last):
File "<string>", line 245, in run_nodebug
File "<module1>", line 5, in <module>
File "C:\Python26\lib\site-packages\matplotlib\figure.py", line 945, in gca
return self.add_subplot(111, **kwargs)
File "C:\Python26\lib\site-packages\matplotlib\figure.py", line 677, in add_subplot
projection_class = get_projection_class(projection)
File "C:\Python26\lib\site-packages\matplotlib\projections\__init__.py", line 61, in get_projection_class
raise ValueError("Unknown projection '%s'" % projection)
ValueError: Unknown projection '3d'
First off, I think mplot3D worked a bit differently in matplotlib version 0.99 than it does in the current version of matplotlib.
Which version are you using? (Try running: python -c 'import matplotlib; print matplotlib."__version__")
I'm guessing you're running version 0.99, in which case you'll need to either use a slightly different syntax or update to a more recent version of matplotlib.
If you're running version 0.99, try doing this instead of using using the projection keyword argument:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D #<-- Note the capitalization!
fig = plt.figure()
ax = Axes3D(fig) #<-- Note the difference from your original code...
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, 16, extend3d=True)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()
This should work in matplotlib 1.0.x, as well, not just 0.99.
Just to add to Joe Kington's answer (not enough reputation for a comment) there is a good example of mixing 2d and 3d plots in the documentation at http://matplotlib.org/examples/mplot3d/mixed_subplots_demo.html which shows projection='3d' working in combination with the Axes3D import.
from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.add_subplot(2, 1, 1)
...
ax = fig.add_subplot(2, 1, 2, projection='3d')
In fact as long as the Axes3D import is present the line
from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.gca(projection='3d')
as used by the OP also works. (checked with matplotlib version 1.3.1)
Import mplot3d whole to use "projection = '3d'".
Insert the command below in top of your script. It should run fine.
from mpl_toolkits import mplot3d
I encounter the same problem, and #Joe Kington and #bvanlew's answer solve my problem.
but I should add more infomation when you use pycharm and enable auto import.
when you format the code, the code from mpl_toolkits.mplot3d import Axes3D will auto remove by pycharm.
so, my solution is
from mpl_toolkits.mplot3d import Axes3D
Axes3D = Axes3D # pycharm auto import
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
and it works well!
As recommended in other comments I found that importing "axes3d" resolved the issue:
from mpl_toolkits.mplot3d import Axes3D
It seems that this is needed if using an older version of matplotlib.pyplot
Try this:
import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.mplot3d import axes3d
fig=plt.figure(figsize=(16,12.5))
ax=fig.add_subplot(2,2,1,projection="3d")
a=ax.scatter(Dataframe['bedrooms'],Dataframe['bathrooms'],Dataframe['floors'])
plt.plot(a)

Categories