I am trying to rotate an embedded plot as a whole (i.e. the x axis of the plot should be in 45 degrees with x axis of embed plot). An example code providing a rotated embedded plot according to How to rotate a simple matplotlib Axes can be found below. The rotation does not seem to rotate the data but just the axis. In addition, I can't yet figure out how to move the embed plot within this figure
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
import matplotlib as mpl
from matplotlib.transforms import Affine2D
import mpl_toolkits.axisartist.floating_axes as floating_axes
def add_subplot_axes(ax,rect,axisbg='w'):
fig = plt.gcf()
box = ax.get_position()
width = box.width
height = box.height
inax_position = ax.transAxes.transform(rect[0:2])
transFigure = fig.transFigure.inverted()
infig_position = transFigure.transform(inax_position)
x = infig_position[0]
y = infig_position[1]
width *= rect[2]
height *= rect[3]
subax = fig.add_axes([x,y,width,height])
x_labelsize = subax.get_xticklabels()[0].get_size()
y_labelsize = subax.get_yticklabels()[0].get_size()
x_labelsize *= rect[2]**0.5
y_labelsize *= rect[3]**0.5
subax.xaxis.set_tick_params(labelsize=x_labelsize)
subax.yaxis.set_tick_params(labelsize=y_labelsize)
return subax
St=np.zeros((150,150))
k=np.random.sample(150)
np.fill_diagonal(np.fliplr(St), k)
fig=plt.figure(figsize=(10,10))
ax=fig.add_subplot(111)
ax.imshow(St,cmap='Greys')
plot_extents = 0, 10, 0, 10
transform = Affine2D().rotate_deg(45)
helper = floating_axes.GridHelperCurveLinear(transform, plot_extents)
ax1 = floating_axes.FloatingSubplot(fig, 111, grid_helper=helper)
ax1.plot(np.arange(0,10),(0,1,2,3,4,5,7,9,10,10))
fig.add_subplot(ax1)
plt.show()
Related
I am trying to plot some meteorological data onto a map and I would like to add an image of a plane using imshow. Plotting i) the trajectory, ii) some contour-data and iii) the image, works fine. But as soon as I add a contourf-plot (see below) the image dissapears!
Any ideas how to fix this?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import cartopy.crs as crs
import cartopy.feature as cfeature
def plot_test():
#DEFINE DATA
x,y = np.meshgrid(np.linspace(0,90,100),np.linspace(0,90,100))
z = x**3 + y**3
#BEGIN FIGURE (IN THIS CASE A MAP, IM PLOTTING METEOROLOGICAL DATA)
fig = plt.figure(figsize = (6,6))
ax1 = plt.axes(projection=crs.PlateCarree(central_longitude=0))
ax1.set_extent([0,90,0,90], crs=crs.PlateCarree())
ax1.coastlines(resolution='auto', color='k')
#EXAMPLE DATA PLOTTED AS CONTOURF
v_max = int(z.max())
v_min = int(z.min())
qcs = ax1.contourf(x, y, z, cmap = "Blues", vmin = v_min, vmax = v_max)
sm = plt.cm.ScalarMappable(cmap="Blues",norm=qcs.norm)
sm._A = []
cbar = plt.colorbar(sm, ax=ax1,orientation="vertical")
cbar.ax.set_ylabel("some contourf data", rotation=90, fontsize = 15)
#PLOT IMAGE OF A PLANE (THIS IS NOT SHOWING UP ON THE PLOT!)
x0 = 50
y0 = 40
img=plt.imread("plane2.png")
ax1.imshow(img,extent=[x0,x0 - 10, y0, y0-10], label = "plane")
plt.show()
without contourf (code from above with lines 14-20 commented out):
with contourf:
Thank you 1000 times #JohanC (see comments). I simply had to place the z-order:
ax1.imshow(img, ...., zorder=3)
which made the plane show up!
Consider a 3D bar plot with custom grid lines:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.ticker import MultipleLocator
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot(111, projection='3d')
ax.xaxis.set_major_locator(MultipleLocator(1))
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.zaxis.set_major_locator(MultipleLocator(2))
nx = 10
ny = 10
colors = cm.tab20(np.linspace(0, 1, nx))
width = depth = 0.1
for x in np.arange(nx):
for y in np.arange(ny):
ax.bar3d(x, y, 0, width, depth, x+y, shade=False, color = colors[x], edgecolor = 'black')
plt.show()
How can I place the bars so that the bars are centered where the grid lines cross each other in the xy plane?
I'm thinking about something like
ax.bar3d(x+0.5*depth, y+0.5*width, ...)
only it is not clear to me what the offset is that matplotlib uses. It should work for all depth and width values.
For 2D bar plots there is an argument for this, align = 'center', but it doesn't seem to work for 3D.
What looks to you as a shift in coordinates is really just the projection in combination with the margins of the axes. Hence even if the bars are correctly positionned in their center they look offset and that offset is dependent on the axes size, viewing angle etc.
The solution to this is in principle given in this Q&A:
Removing axes margins in 3D plot
You would center the bars by subtracting half of their width and add a patch to remove the margin of the zaxis. Then setting the lower z limit to 0 pins the bars to the grid and makes them look centered for any viewing angle.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.ticker import MultipleLocator
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.axis3d import Axis
def _get_coord_info_new(self, renderer):
mins, maxs, cs, deltas, tc, highs = self._get_coord_info_old(renderer)
correction = deltas * [0,0,1.0/4]
mins += correction
maxs -= correction
return mins, maxs, cs, deltas, tc, highs
if not hasattr(Axis, "_get_coord_info_old"):
Axis._get_coord_info_old = Axis._get_coord_info
Axis._get_coord_info = _get_coord_info_new
fig = plt.figure(figsize=(20, 10))
ax = fig.add_subplot(111, projection='3d')
ax.xaxis.set_major_locator(MultipleLocator(1))
ax.yaxis.set_major_locator(MultipleLocator(1))
ax.zaxis.set_major_locator(MultipleLocator(2))
nx = 10
ny = 10
colors = cm.tab20(np.linspace(0, 1, nx))
width = depth = 0.1
for x in np.arange(nx):
for y in np.arange(ny):
ax.bar3d(x-width/2., y-depth/2., 0, width, depth, x+y, shade=False,
color = colors[x], edgecolor = 'black')
ax.set_zlim(0,None)
plt.show()
I want to convert a plot generated with matplotlib to an rgb array. In my case, I want to draw two circles using matplotlib. Currently, there are two problems:
You can still see the space taken by the axes
The circles aren't circles anymore in the resulting rgb array
Here is the code so far:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import numpy as np
Generate the plot:
def drawImage(color, posx, posy, radius):
posx_left, posx_right = posx
posy_left, posy_right = posy
radius_left, radius_right = radius
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.gca()
ax.axis('off')
ax.set_axis_off()
ax = fig.add_subplot(1, 1, 1)
circle_left = plt.Circle((posx_left, posy_left), radius=radius_left,color=color)
ax.add_patch(circle_left)
circle_right = plt.Circle((posx_right, posy_right), radius=radius_right,color=color)
ax.add_patch(circle_right)
fig.tight_layout(pad=0)
fig.canvas.draw()
width, height = fig.get_size_inches() * fig.get_dpi()
img = np.fromstring(fig.canvas.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3)
return img
Generate plot and save as array:
color = "blue"
radius = 0.2, 0.12
posx = 0.0,0.8
posy = 0.3,0.7
img = drawImage(color,posx,posy,radius)
plt.imshow(img)
I would like to add a fourth dimension to the scatter plot by defining the ellipticity of the markers depending on a variable. Is that possible somehow ?
EDIT:
I would like to avoid a 3D-plot. In my opinion these plots are usually not very informative.
You can place Ellipse patches directly onto your axes, as demonstrated in this matplotlib example. To adapt it to use eccentricity as your "third dimension") keeping the marker area constant:
from pylab import figure, show, rand
from matplotlib.patches import Ellipse
import numpy as np
import matplotlib.pyplot as plt
N = 25
# ellipse centers
xy = np.random.rand(N, 2)*10
# ellipse eccentrities
eccs = np.random.rand(N) * 0.8 + 0.1
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
A = 0.1
for pos, e in zip(xy, eccs):
# semi-minor, semi-major axes, b and a:
b = np.sqrt(A/np.pi * np.sqrt(1-e**2))
a = A / np.pi / b
ellipse = Ellipse(xy=pos, width=2*a, height=2*b)
ax.add_artist(ellipse)
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
show()
Of course, you need to scale your marker area to your x-, y- values in this case.
You can use colorbar as the 4th dimension to your 3D plot. One example is as shown below:
import matplotlib.cm as cmx
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
def scatter3d(x,y,z, cs, colorsMap='jet'):
cm = plt.get_cmap(colorsMap)
cNorm = matplotlib.colors.Normalize(vmin=min(cs), vmax=max(cs))
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x, y, z, c=scalarMap.to_rgba(cs))
scalarMap.set_array(cs)
fig.colorbar(scalarMap,label='Test')
plt.show()
x = np.random.uniform(0,1,50)
y = np.random.uniform(0,1,50)
z = np.random.uniform(0,1,50)
so scatter3D(x,y,z,x+y) produces:
with x+y being the 4th dimension shown in color. You can add your calculated ellipticity depending on your specific variable instead of x+y to get what you want.
To change the ellipticity of the markers you will have to create them manually as such a feature is not implemented yet. However, I believe you can show 4 dimensions with a 2D scatter plot by using color and size as additional dimensions. You will have to take care of the scaling from data to marker size yourself. I added a simple function to handle that in the example below:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(60,4)
def scale_size(data, data_min=None, data_max=None, size_min=10, size_max=60):
# if the data limits are set to None we will just infer them from the data
if data_min is None:
data_min = data.min()
if data_max is None:
data_max = data.max()
size_range = size_max - size_min
data_range = data_max - data_min
return ((data - data_min) * size_range / data_range) + size_min
plt.scatter(data[:,0], data[:,1], c=data[:,2], s=scale_size(data[:,3]))
plt.colorbar()
plt.show()
Result:
I am trying to make a polar plot that goes 180 degrees instead of 360 in Matplotlib similar to http://www.mathworks.com/matlabcentral/fileexchange/27230-half-polar-coordinates-figure-plot-function-halfpolar in MATLAB. Any ideas?
The following works in matplotlib 2.1 or higher. There is also an example on the matplotlib page.
You may use a usual polar plot, ax = fig.add_subplot(111, polar=True) and confine the theta range. For a half polar plot
ax.set_thetamin(0)
ax.set_thetamax(180)
or for a quarter polar plot
ax.set_thetamin(0)
ax.set_thetamax(90)
Complete example:
import matplotlib.pyplot as plt
import numpy as np
theta = np.linspace(0,np.pi)
r = np.sin(theta)
fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
c = ax.scatter(theta, r, c=r, s=10, cmap='hsv', alpha=0.75)
ax.set_thetamin(0)
ax.set_thetamax(180)
plt.show()
The example code in official matplotlib documentation may obscure things a little bit if someone just needs a simple quarter of half plot.
I wrote a code snippet that may help someone who is not that familiar with AxisArtists here.
"""
Reference:
1. https://gist.github.com/ycopin/3342888
2. http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#axisartist
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.projections import PolarAxes
from mpl_toolkits.axisartist.floating_axes import GridHelperCurveLinear, FloatingSubplot
import mpl_toolkits.axisartist.grid_finder as gf
def generate_polar_axes():
polar_trans = PolarAxes.PolarTransform()
# Setup the axis, here we map angles in degrees to angles in radius
phi_degree = np.arange(0, 90, 10)
tlocs = phi_degree * np.pi / 180
gl1 = gf.FixedLocator(tlocs) # Positions
tf1 = gf.DictFormatter(dict(zip(tlocs, map(str, phi_degree))))
# Standard deviation axis extent
radius_min = 0
radius_max = 1
# Set up the axes range in the parameter "extremes"
ghelper = GridHelperCurveLinear(polar_trans, extremes=(0, np.pi / 2, # 1st quadrant
radius_min, radius_max),
grid_locator1=gl1,
tick_formatter1=tf1,
)
figure = plt.figure()
floating_ax = FloatingSubplot(figure, 111, grid_helper=ghelper)
figure.add_subplot(floating_ax)
# Adjust axes
floating_ax.axis["top"].set_axis_direction("bottom") # "Angle axis"
floating_ax.axis["top"].toggle(ticklabels=True, label=True)
floating_ax.axis["top"].major_ticklabels.set_axis_direction("top")
floating_ax.axis["top"].label.set_axis_direction("top")
floating_ax.axis["top"].label.set_text("angle (deg)")
floating_ax.axis["left"].set_axis_direction("bottom") # "X axis"
floating_ax.axis["left"].label.set_text("radius")
floating_ax.axis["right"].set_axis_direction("top") # "Y axis"
floating_ax.axis["right"].toggle(ticklabels=True)
floating_ax.axis["right"].major_ticklabels.set_axis_direction("left")
floating_ax.axis["bottom"].set_visible(False) # Useless
# Contours along standard deviations
floating_ax.grid(True)
floating_ax.set_title("Quarter polar plot")
data_ax = floating_ax.get_aux_axes(polar_trans) # return the axes that can be plotted on
return figure, data_ax
if __name__ == "__main__":
# Plot data onto the defined polar axes
fig, ax = generate_polar_axes()
theta = np.random.rand(10) * np.pi / 2
radius = np.random.rand(10)
ax.scatter(theta, radius)
fig.savefig("test.png")