Matplotlib issue x and y label for multi axes figure - matplotlib

import matplotlib
import matplotlib.pyplot as plt
import numpy as nm
x = nm.linspace(start=0,stop=20,num=30)
fig=plt.figure()
ax1 = fig.add_axes([0,0.6,0.6,0.4])
ax2 = fig.add_axes([0,0,0.8,0.4])
ax1.plot(x,nm.sin(x))
ax1.set_xlabel('x',fontsize=15,color='r')
ax1.set_ylabel('sin(x)',fontsize=15,color='r')
ax2.plot(x,nm.cos(x))
ax2.set_xlabel('x',fontsize=15,color='r')
ax2.set_ylabel('cos(x)',fontsize=15,color='r')
plt.show()
The output I am not able to see the xlabel for ax2 and not able to see both y label for ax1 and ax2..The image is present below:
enter code hereenter image description here

This is expected as you are asking to create an axes that is aligned with the left edge of the figure by using fig.add_axes([0,...]). Same thing for the bottom axes, which you have aligned to the bottom-left of the figure using fig.add_axes([0,0,...]).
Increase the first value e.g. fig.add_axes([0.125,...]) to leave room for the axes decorations on the left or bottom of the axes.
It is generally recommended to use the subplots functions (such as add_subplot, plt.subplots or GridSpec) so that these details are handled automatically.

Related

How to entend the area/boudaries that shows the data from a Axes3D with matplolib when using the set_box_aspect zoom

I'm trying to zoom in a 3D plot. I'm using the ax.set_box_aspect() fonction. When doing so, the axis are zoomed in, they appear bigger, but the area where the data can be seen stay at the same size as before (the plot are not using the total available space).
The aim in the end is to have two axis, the first one 3d, the other one 2d. I would have wanted the first plot to take all the space available at the top half of the figure.
Here is the code before the Zoom
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#---- generate data
nn = 100
X = np.random.randn(nn)*20 + 0
Y = np.random.randn(nn)*50 + 30
Z = np.random.randn(nn)*10 + -5
#---- check aspect ratio
asx, asy, asz = np.ptp(X), np.ptp(Y), np.ptp(Z)
fig = plt.figure(figsize=(15,15))
ax = fig.add_subplot(211, projection='3d')
#---- set box aspect ratio
ax.set_box_aspect((asx,asy,asz))
scat = ax.scatter(X, Y, Z, c=X+Y+Z, s=500, alpha=0.8)
ax.set_xlabel('X-axis'); ax.set_ylabel('Y-axis'); ax.set_zlabel('Z-axis')
ax = fig.add_subplot(212)
plt.show()
Before using the zoom
And now when I zoom in, the scatter is limitted in a square frame :
ax.set_box_aspect((asx,asy,asz), zoom = 2 )
After using the zoom
(The data used for the plot doesn't matter here, it is just to showcase my issue.)
I tried changing the axis limit with set_xlim3d or set_xlim, but in either case, the result is the same.
It seems like the showing area (I can't find the right word for it) stays a square no matter what.
I didn't find any usefull information on that matter online, (maybe from the lack of vocabulary to describe my problem).

how to change color of axis in 3d matplotlib figure?

The color of the axis (x, y, z) in a 3d plot using matplotlib is black by default. How do you change the color of the axis? Or better yet, how do you make them invisible?
%matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.xaxis.set_visible(False) # doesn't do anything
And there doesn't seem to be a ax.xaxis.set_color function. Any thoughts on how to make the axis invisible or change the color?
You can combine your method with the approach provided here. I am showing an example that affects all three axes. In Jupyter Notebook, using tab completion after ax.w_xaxis.line., you can discover other possible options
ax.w_xaxis.line.set_visible(False)
ax.w_yaxis.line.set_color("red")
ax.w_zaxis.line.set_color("blue")
To change the tick colors, you can use
ax.xaxis._axinfo['tick']['color']='r'
ax.yaxis._axinfo['tick']['color']='g'
ax.zaxis._axinfo['tick']['color']='b'
To hide the ticks
for line in ax.xaxis.get_ticklines():
line.set_visible(False)

changing the size of subplots with matplotlib

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')

How to overlay one pyplot figure on another

Searching easily reveals how to plot multiple charts on one figure, whether using the same plotting axes, a second y axis or subplots. Much harder to uncover is how to overlay one figure onto another, something like this:
That image was prepared using a bitmap editor to overlay the images. I have no difficulty creating the individual plots, but cannot figure out how to combine them. I expect a single line of code will suffice, but what is it? Here is how I imagine it:
bigFig = plt.figure(1, figsize=[5,25])
...
ltlFig = plt.figure(2)
...
bigFig.overlay(ltlFig, pos=[x,y], size=[1,1])
I've established that I can use figure.add_axes, but it is quite challenging getting the position of the overlaid plot correct, since the parameters are fractions, not x,y values from the first plot. It also [it seems to me - am I wrong?] places constraints on the order in which the charts are plotted, since the main plot must be completed before the other plots are added in turn.
What is the pyplot method that achieves this?
To create an inset axes you may use mpl_toolkits.axes_grid1.inset_locator.inset_axes.
Position of inset axes in axes coordinates
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
fig, ax= plt.subplots()
inset_axes = inset_axes(ax,
width=1, # inch
height=1, # inch
bbox_transform=ax.transAxes, # relative axes coordinates
bbox_to_anchor=(0.5,0.5), # relative axes coordinates
loc=3) # loc=lower left corner
ax.axis([0,500,-.1,.1])
plt.show()
Position of inset axes in data coordinates
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
fig, ax= plt.subplots()
inset_axes = inset_axes(ax,
width=1, # inch
height=1, # inch
bbox_transform=ax.transData, # data coordinates
bbox_to_anchor=(250,0.0), # data coordinates
loc=3) # loc=lower left corner
ax.axis([0,500,-.1,.1])
plt.show()
Both of the above produce the same plot
(For a possible drawback of this solution see specific location for inset axes)

secondary Y axis position matplotlib

I need to change the secondary Y axis position on a matplotlib plot.
It's like a subplot inside the same plot.
In the image below, my secondary Y axis starts at the same position as first y axis. I need that the secondary Y axis starts about at the "18" position of the first Y axis, with a smaller scale (red line).
If I understand the question, you want a twinx axis, as #kikocorreoso says, but you also want to compress it, so it only takes up the upper portion of the y axis.
You can do this by just setting the ylim larger than you need it, and explicitly setting the yticks. Here's an example with some random data
import matplotlib.pyplot as plt
import numpy as np
data = [np.random.normal(np.random.randint(0,5),4,25) for _ in range(25)] # some random data
fig=plt.figure()
ax1=fig.add_subplot(111)
ax2=ax1.twinx()
ax1.set_ylim(-5,25)
ax2.set_ylim(0,14)
ax2.set_yticks([10,12,14]) # ticks below 10 don't show up
ax1.boxplot(data)
ax2.plot(np.linspace(0,26,50),12.+2.*np.sin(np.linspace(0,2.*np.pi,50))) # just a random line
plt.show()
If I understood correctly seeing the figure you posted you want a second y-axis. You can do this using plt.twinx. An example could be like the following:
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.twinx()
plt.plot([5,4,5])
plt.show()