Trying to add a 3d subplot to a matplotlib figure - matplotlib

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.

Related

Is there a function in plotly that is equivalent to plt.axes('scaled') in matplotlib for the aspect ratio of a graph?

I want to plot some coordinates using Plotly express because it allows me a more interactive approach, but I can not find the way to control the scale in the axis in the way I can manage with matplotlib.pyplot in one single line
plt.axis("scaled")
Could you please share some suggestions? Thanks.
Here is the code using Plotly express:
fig = px.scatter(coordinates_utm, x='EASTING', y='NORTHING', title=name,
hover_name=coordinates_utm.index,
hover_data={'NORTHING':':.6f','EASTING': ':.6f'})
fig.add_trace(px.scatter(coordinates_utm_lineal, x='x', y='ylineal',color_discrete_sequence=['red']).data[0])
Here is the code using plt:
fig.show()
plt.figure()
plt.scatter(coordinates_utm_lineal.x,coordinates_utm_lineal.ylineal,s=2)
plt.scatter(coordinates_utm.EASTING,coordinates_utm.NORTHING, s=2)
plt.axis("scaled")
plt.show()
This is my current output
Sadly, you didn't provide a fully reproducible example, so I'm going to create my own.
Also, I'm not really familiar with plt.axis("scaled"), as I usually use plt.axis("equal"). Reading the documentation associated to plt.axis, they appear to be somewhat similar. See if the following answer can satisfy your needs.
import plotly.express as px
import numpy as np
t = np.linspace(0, 2*np.pi)
x = np.cos(t)
y = np.sin(t)
fig = px.scatter(x=x, y=y)
fig.layout.yaxis.scaleanchor="x"
fig.show()

How to control the axis units in a map made with astropy and matplotlib?

When using astropy and matplotlib to create a map, the units in the right ascension axis are deg/min/sec, instead of h/m/s. I do not find an easy way in astropy to select the units h/m/s.
For example, if I try to reproduce the map of the Horsehead nebula as in the documentation of astropy.wcs, I get a R.A. axis in deg/min/sec.
The code is simply:
from matplotlib import pyplot as plt
from astropy.io import fits
from astropy.wcs import WCS
from astropy.utils.data import get_pkg_data_filename
filename = get_pkg_data_filename('tutorials/FITS-images/HorseHead.fits')
hdu = fits.open(filename)[0]
wcs = WCS(hdu.header)
fig = plt.figure()
fig.add_subplot(111, projection=wcs)
plt.imshow(hdu.data, origin='lower', cmap=plt.cm.viridis)
plt.xlabel('RA')
plt.ylabel('Dec')
plt.show()
It is supposed to produce this:
correct units
but I get that:
wrong units
You can use:
ax = fig.gca()
ra = ax.coords[0]
ra.set_format_unit('hour')
e.g. as specified here: http://docs.astropy.org/en/stable/visualization/wcsaxes/controlling_axes.html
However, when I ran the same example, it defaulted to hours, so I'm not sure what configuration you have set that defaulted to degrees instead.

Matplotlib: Discrete colorbar fails for custom labels

I faced a serious problem when I was trying to add colorbar to scatter plot which indicates in which classes individual sample belongs to. The code works perfectly when classes are [0,1,2] but when the classes are for example [4,5,6] chooses colorbar automatically color values in the end of colormap and colorbar looks blue solid color. I'm missing something obvious but I just can't figure out what it is.
Here is the example code about the problem:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(1 , figsize=(6, 6))
plt.scatter(datapoints[:,0], datapoints[:,1], s=20, c=labels, cmap='jet', alpha=1.0)
plt.setp(ax, xticks=[], yticks=[])
cbar = plt.colorbar(boundaries=np.arange(len(classes)+1)-0.5)
cbar.set_ticks(np.arange(len(classes)))
cbar.set_ticklabels(classes)
plt.show()
Variables can be for example
datapoints = np.array([[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7]])
labels = np.array([4,5,6,4,5,6,4])
classes = np.array([4,5,6])
Correct result is got when
labels = np.array([0,1,2,0,1,2,0])
In my case I want it to work also for classes [4,5,6]
The buoundaries need to be in data units. Meaning, if your classes are 4,5,6, you probably want to use boundaries of 3.5, 4.5, 5.5, 6.5.
import matplotlib.pyplot as plt
import numpy as np
datapoints = np.array([[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7]])
labels = np.array([4,5,6,4,5,6,4])
classes = np.array([4,5,6])
fig, ax = plt.subplots(1 , figsize=(6, 6))
sc = ax.scatter(datapoints[:,0], datapoints[:,1], s=20, c=labels, cmap='jet', alpha=1.0)
ax.set(xticks=[], yticks=[])
cbar = plt.colorbar(sc, ticks=classes, boundaries=np.arange(4,8)-0.5)
plt.show()
If you wanted to have the boundaries determined automatically from the classes, some assumption must me made. E.g. if all classes are subsequent integers,
boundaries=np.arange(classes.min(), classes.max()+2)-0.5
In general, an alternative would be to use a BoundaryNorm, as shown e.g. in Create a discrete colorbar in matplotlib
or How to specify different color for a specific year value range in a single figure? (Python) or python colormap quantisation (matplotlib)

Plots getting replaced instead of showing a new plot

I am trying to create multiple plots in my Jupyter notebook. However, when I create one, it replaces the one before it instead of creating a brand new graph. Ex.
#plotting revenue_adj vs vote_average data
df.plot.scatter(x='revenue_adj',y='vote_average',s=.5,title='Average Movie Vote per Budget',figsize=(8,5));
creates a scatter plot, but when I try to plot below it (on a new code line),
df.groupby('genres')['vote_average'].mean().plot()
it replaces the above plot instead of creating a new one under that code. What is going on?
Remember, the plotting functions of pandas use actually matplotlib.
So you can use matplotlib figure() or subplots() functions to create new figures:
import matplotlib.pyplot as plt
fig = plt.figure()
df.plot.scatter()
fig = plt.figure()
df.plot.scatter()
# | or using subplots()
fig, ax = plt.subplots(1,2)
df.plot.scatter(ax=ax[0])
df.plot.scatter(ax=ax[1])

Cannot create a 3D axes in matplotlib

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.