I lose my image from a subplot when I shift the image.
(The code is run in Jupyter Lab):
from mpl_toolkits.axes_grid1 import host_subplot
from mpl_toolkits import axisartist
hostImage = host_subplot(221, axes_class=axisartist.Axes)
from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox
import matplotlib.image as mpimg
test_image = mpimg.imread('testImage.png')
imagebox = OffsetImage(test_image, zoom=1)
ab = AnnotationBbox(imagebox, (-0.0014, 0), box_alignment=(1, 0))
hostImage.add_artist(ab)
The image can still be seen with the above configuration.
Next, when I change parameters the image vanishes:
Shifting the image to the left changing line 7
ab = AnnotationBbox(imagebox, (-0.0025, 0), box_alignment=(1, 0))
to
ab = AnnotationBbox(imagebox, (-0.5, 0), box_alignment=(1, 0))
Changing the matrix layout of the subplots changing line
hostImage = host_subplot(221, axes_class=axisartist.Axes)
to
hostImage = host_subplot(111, axes_class=axisartist.Axes)
-> How can I show everything I add to a subplot (more or less) regardless how far off it may be from the axes 'central part' (the area spanned by the two axes, 'axes' in the sense of a plot)?
Using the plt.tight_layout() method did not help.
Here is the test image I used (the red rhomboid).
%%%%%%%%%%%
To make it clearer what I really want to achieve (practical background of the question):
I have line plots showing measurement data of about 30 sensors which are positioned in the real world in a rather geometrically complex 3D measurement setup. The position of the sensors is essential for anybody trying to understand the chart. So the image serves as a kind of 3D legend for the chart. In a single plot I show data of about 5-6 sensors (more sensors in single chart would make it unreadable).
See this real example (work in progress where I stopped to post my question):
image of the real case
This example I established by creating a second subplot below the subplot with the curves. This second suplot has hidden axes (in the sense of plural of axis). It already is a workable solution and my current baseline.
By the way, for this reason I want the image to be rather below the plot in order not to 'waste' horizontal space for the chart where I plot curves.
So the '3D image legend' is integral part of the finally exported 'all-in-one' plot (.png)
The .pngs go into my written report which is my ultimate goal.
In the report I could also add each image corresponding to a plot by hand, but having all info (plot and image) included in one-in-all matplotlib figures makes it more convenient to establish the report and also less error-prone (pairing wrong images and plots, since I have many sensors and many configurations thus creating quite a number of such plots).
What triggered my question beyond my above solution already established:
I want to finally place labels (matplotlib annotations) as 'overlay' on the image with the sensor names on top of the image.
And then connect these labels via arrow lines with the corresponding curves of the plot. This would make it very clear and convenient to the reader to understand which plot curve corresponds to which sensor position in the image -> kind of '3D legend'.
I had found ConnectionPatch as a solution for drawing lines between subplots but I got an error message which I ultimately did not want to try to resolve but choose the approach:
Have the image as part of the very same subplot of the curves because connecting labels within a subplot is easy (actually you can see in the image I uploaded already such sensor name labels placed along the right y-axis).
Why do I use host_subplot?
I have up to five y-axes in my plot (I am aware that this high number of y-axis may be questionable but it is please not what I want to discuss in this post) and I understood having more than 2 additional y-axis is possible only with host_subplot using .twinx().
P.S.:
After all I think I should for now lower my high expectations and stick with my workable solution of two subplots and just renounce on the possibility of connecting labels in the second subplot with curves in the first subplot.
Matplotlib 3.5 (or presumably better)
If you are using Matplotlib 3.5 (or presumably better), this works for what you want, I think (or close):
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as axisartist
hostImage = host_subplot(221, axes_class=axisartist.Axes)
from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox
import matplotlib.image as mpimg
test_image = mpimg.imread('testImage.png')
imagebox = OffsetImage(test_image, zoom=1)
ab = AnnotationBbox(imagebox, (-0.0025, 0), box_alignment=(1, 0))
hostImage.add_artist(ab)
hostImage.figure.subplots_adjust(left=0.69) # based on https://matplotlib.org/stable/tutorials/intermediate/tight_layout_guide.html saying how to manually adjust
hostImage.figure.set_size_inches((18, 10)) # from https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/figure.py; also see drevicko's comment https://stackoverflow.com/a/638443/8508004
hostImage.figure.savefig("my_image_test.png") # fix for `hostImage.savefig("my_image_test.png")`, based on https://forum.freecodecamp.org/t/attribute-error-axessubplot-object-has-no-attribute-savefig/46025
This will show the same view of the produced plot in both the direct in JupyterLab output and in the image file produced. (The actual size will probably be slightly different, with the image file displaying better resolution.) **If you don't want to produce an image file, then you can remove the last two lines and just include the adjustment **,figure.subplots_adjust(left=0.69) , to account for the Annotation box being added.
I put pertinent sources in the comments for each line.
My test image was wide and short so you may need to adjust figure.subplots_adjust(left=0.69) to what works for you. (Now I don't like that I had to stumble around trying very high and low versions of the left value for figure.subplots_adjust(), and then hone in on a just-right setting but it worked. I will say that usually I set the figure size before making the subplots, such as here, and maybe doing it that way makes it seem less experimenting is necessary to get it working. But the fact the manual adjustment is mentioned in discussion of tight_layout in Matplotlib's documentation, in regards to elements going outside the figure area, makes me think it happens that you need to do some adjusting now and then.)
Here I use hostImage.figure.set_size_inches((18, 10)). Maybe you don't need yours as wide?
Code for checking Matplotlib version:
import matplotlib
print (matplotlib.__version__ )
Matplotlib versions prior to 3.5 (or maybe specifically 3.2.1?)
The code above wasn't working with Matplotlib 3.2.1 with all else the same. (In launches of Jupyter sessions served via MyBinder from here before running %pip install matplotlib --upgrade in a cell and restarting the kernel.) The image produced was good but the output directly in the Jupyter notebook was cutoff and only showing a fragment.
This code block below works for what you want, I think (or close), if using Matplotlib 3.2.1. Since I couldn't get the direct output in the Jupyter cell where I was using Matplotplib 3.2.1 to display correctly, this just displays the plot from the associated image file produced.
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as axisartist
hostImage = host_subplot(221, axes_class=axisartist.Axes)
from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox
import matplotlib.image as mpimg
test_image = mpimg.imread('testImage.png')
imagebox = OffsetImage(test_image, zoom=1)
ab = AnnotationBbox(imagebox, (-0.0025, 0), box_alignment=(1, 0))
hostImage.add_artist(ab)
hostImage.figure.subplots_adjust(left=0.69) # based on https://matplotlib.org/stable/tutorials/intermediate/tight_layout_guide.html saying how to manually adjust
hostImage.figure.set_size_inches((18, 10)) # from https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/figure.py; also see drevicko's comment https://stackoverflow.com/a/638443/8508004
hostImage.figure.savefig("my_image_test.png") # fix for `hostImage.savefig("my_image_test.png")`, based on https://forum.freecodecamp.org/t/attribute-error-axessubplot-object-has-no-attribute-savefig/460255
hostImage.figure.clf() # using this so, Jupyter won't display the Matplotlib plot object; instead we'll show the image file
from IPython.display import Image
Image(filename="my_image_test.png")
How things are working for the shared lines I added is covered above.
Optionally when using Matplotlib 3.2.1 with code like here, to not also show the matplotlib cruft, such as something like <Figure size 1296x720 with 0 Axes>, you can split running this between two cells.
First cell's code:
%%capture
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as axisartist
hostImage = host_subplot(221, axes_class=axisartist.Axes)
from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox
import matplotlib.image as mpimg
test_image = mpimg.imread('testImage.png')
imagebox = OffsetImage(test_image, zoom=1)
ab = AnnotationBbox(imagebox, (-0.0025, 0), box_alignment=(1, 0))
hostImage.add_artist(ab)
hostImage.figure.subplots_adjust(left=0.69) # based on https://matplotlib.org/stable/tutorials/intermediate/tight_layout_guide.html saying how to manually adjust
hostImage.figure.set_size_inches((18, 10)) # from https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/figure.py; also see drevicko's comment https://stackoverflow.com/a/638443/8508004
hostImage.figure.savefig("my_image_test.png") # fix for `hostImage.savefig("my_image_test.png")`, based on https://forum.freecodecamp.org/t/attribute-error-axessubplot-object-has-no-attribute-savefig/460255
hostImage.figure.clf() # using this so, Jupyter won't display the Matplotlib plot object; instead we'll show the image file
Second cell's code:
from IPython.display import Image
Image(filename="my_image_test.png")
The first cell will show no output of any kind now due to the %%capture cell magic.
UPDATE:
(code below only tested with Matplotlib 3.5.)
Some options based on addition of sample figure OP is using and additional information in comment here, I suggest starting over with simpler subplot use for arranging the two elements. (If it was much more complex, I'd suggest other methods for compositing the two elements. Options would include: If just for presenting in Jupyter, ipywidgets can be used for layout. Pillow and ReportLab can be useful if making a publication-quality figure is the goal.)
!curl -o testImage.png https://owncloud.tuwien.ac.at/index.php/s/3caJsb2PcwN7HdU/download
#based on https://matplotlib.org/stable/gallery/subplots_axes_and_figures/subplots_demo.html
# and https://www.moonbooks.org/Articles/How-to-insert-an-image-a-picture-or-a-photo-in-a-matplotlib-figure/
# and https://nbviewer.org/gist/fomightez/4c2116e50f080b1305c41b9ac70df124#Solution
# axis off for lower plot based on https://stackoverflow.com/a/10035974/8508004
import matplotlib.pyplot as plt
from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox
import matplotlib.image as mpimg
fig, axs = plt.subplots(2,1,figsize=(4, 8))
#fig.suptitle('Vertically stacked subplots')
axs[0].grid()
axs[1].grid()
test_image = mpimg.imread('testImage.png')
imagebox = OffsetImage(test_image, zoom=1)
ab = AnnotationBbox(imagebox, (0.5,0.5))
axs[1].add_artist(ab)
axs[1].axis('off');
Or:
!curl -o testImage.png https://owncloud.tuwien.ac.at/index.php/s/3caJsb2PcwN7HdU/download
#based on https://matplotlib.org/stable/gallery/subplots_axes_and_figures/subplots_demo.html
# and https://www.moonbooks.org/Articles/How-to-insert-an-image-a-picture-or-a-photo-in-a-matplotlib-figure/
# and https://nbviewer.org/gist/fomightez/4c2116e50f080b1305c41b9ac70df124#Solution
# axis turned off for lower plot based on https://stackoverflow.com/a/10035974/8508004
import matplotlib.pyplot as plt
from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox
import matplotlib.image as mpimg
# data to plot based on https://stackoverflow.com/a/17996099/8508004 and converting it
# to work with subplot method
fig, axs = plt.subplots(2,1)
plt.subplots_adjust(hspace=1.8) # to move the bottom plot down some so not covering the top small one
#fig.suptitle('Vertically stacked subplots')
axs[0].plot(range(15))
axs[0].set_xlim(-7, 7)
axs[0].set_ylim(-7, 7)
axs[0].set_aspect('equal')
axs[1].grid()
test_image = mpimg.imread('testImage.png')
imagebox = OffsetImage(test_image, zoom=1)
ab = AnnotationBbox(imagebox, (0.5,0.5))
axs[1].add_artist(ab)
axs[1].axis('off');
Or if want to save the figure something like:
!curl -o testImage.png https://owncloud.tuwien.ac.at/index.php/s/3caJsb2PcwN7HdU/download
#based on https://matplotlib.org/stable/gallery/subplots_axes_and_figures/subplots_demo.html
# and https://www.moonbooks.org/Articles/How-to-insert-an-image-a-picture-or-a-photo-in-a-matplotlib-figure/
# and https://nbviewer.org/gist/fomightez/4c2116e50f080b1305c41b9ac70df124#Solution
# axis turned off for lower plot based on https://stackoverflow.com/a/10035974/8508004
import matplotlib.pyplot as plt
from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox
import matplotlib.image as mpimg
# data to plot based on https://stackoverflow.com/a/17996099/8508004 and converting it
# to work with subplot method
fig, axs = plt.subplots(2,1)
plt.subplots_adjust(hspace=0.3) # to move the bottom plot down some so not covering the top small one
#fig.suptitle('Vertically stacked subplots')
axs[0].plot(range(15))
axs[0].set_xlim(-7, 7)
axs[0].set_ylim(-7, 7)
axs[0].set_aspect('equal')
axs[1].grid()
test_image = mpimg.imread('testImage.png')
imagebox = OffsetImage(test_image, zoom=1)
ab = AnnotationBbox(imagebox, (0.5,0.5))
axs[1].add_artist(ab)
axs[1].axis('off')
# to accomodate this adjustment in the figure that gets saved via `plt.savefig()`, increase figure size
fig.set_size_inches((4, 7)) # from https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/figure.py; also see drevicko's comment
plt.savefig("stacked.png");
I'm not sure while the size changes on the top plot if you set the size so you can accomodate them but there's some honing on the right numbers needed there.
Edit on 2022-09-28:
I have found a solution for my case by browsing the help/py-code of matplotlib.offsetbox.AnnotationBbox:
The desired effect can be achieved by modifying the argument xybox of AnnotationBbox like so, for example
ab = AnnotationBbox(imagebox, xy = (1, 0), xybox = (2.0, 1.0), box_alignment=(1, 0))
Setting xybox = (2.0, 1.0), hence the x-value to 2.0 shifts the image far to the right of the plot area.
so I am making 4 types of plots in matplotlib through functions. Those include Pie Charts, Line Charts, Scatter Plot and area graphs. I want to get a numpy array of it, so I can display it using opencv2 or something else on django. I have tried this so far:
import matplotlib.pyplot as plt
import numpy as np
# Make a random plot...
fig = plt.figure()
fig.add_subplot(111)
# If we haven't already shown or saved the plot, then we need to
# draw the figure first...
fig.canvas.draw()
# Now we can save it to a numpy array.
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
But the problem is I cannot use a plot here, I have to use a figure which I don't want to use. I tried doing plt.plot([1,2,3,4,5]) for line graph as a test, but it turns out it returns a list, while I need a figure to use the tostring_rgb() What should be the alternative to this?
EDIT:
Suggested in comments for another question, I am not wanting to make a figure, I want to make a normal Plot with plt.plot() of line graph, and also plt.pie()
I have a 2D array that I need to save as a png. I also need to add a text label to the image. So far, I have tried two approaches, none of which is optimal:
I use the matplotlib.image module to save the array directly as an image:
matplotlib.image.imsave(FILENAME, ARRAY, cmap=plt.cm.binary)
However I am unable to add text using that command. I could use PIL to read and edit after saving the raw images, but the I/O cost on a large data set would be unacceptable.
I use the pyplot interface to convert the array to a figure and then add a legend. However when I save it as a file, there is unnecessary whitespace. I have tried turning axes off, setting padding to 0 etc., but there is always some whitespace margin I cannot get rid of:
import matplotlib.pyplot as plt
plt.imshow(ARRAY, cmap=plt.cm.binary)
plt.axis('off')
plt.savefig(FILENAME, dpi=100, pad_inches=0.0, bbox_inches='tight')
Is there a way to generate an image from a 2D array, overlay text, and save as .png speedily with no whitespace? Preferably a solution using matplotlib/PIL, but if there's anything better out there, I can look into it.
I was able to solve my problem by using an object oriented approach from the start:
import matplotlib.pyplot as plt
fig = plt.figure(dpi=100, tight_layout=True, frameon=False, figsize=(resolution/100.,resolution/100.)) # dpi & figsize of my choosing
fig.figimage(ARRAY, cmap=plt.cm.binary)
fig.text(X,Y,TEXT, size='medium', backgroundcolor='white', alpha=0.5)
plt.savefig(FILENAME)
plt.close(fig)
Additional documentation for the figure class can be found here.
Note: For sizing figures, I found this relationship useful:
size in inches = resolution in pixels / DPI
This question is related to a comment on another question.
In matplotlib/python, I am trying to rasterize a specific element in my image and save it to eps. The issue is that when saving to EPS (but not SVG or PDF), a black background appears behind the rasterized element.
Saving to PDF and converting to EPS does not seem to be a reasonable solution, as there are weird pdf2ps and pdftops conversion issues that make understanding bounding boxes very ... scary (or worse, seemingly inconsistent). My current work around involves a convoluted process of saving in svg and export in Inkscape, but this should also not be required.
Here is the sample code needed to reproduce the problem. Matplotlib and Numpy will be needed. If the file is saved to mpl-issue.py, then it can be run with:
python mpl-issue.py
#!/usr/bin/env python
# mpl-issue.py
import numpy as np
import matplotlib as mpl
# change backend to agg
# must be done prior to importing pyplot
mpl.use('agg')
import matplotlib.pyplot as plt
def transparencytest():
# create a figure and some axes
f = plt.figure()
a = {
'top': f.add_subplot(211),
'bottom': f.add_subplot(212),
}
# create some test data
# obviously different data on the subfigures
# just for demonstration
x = np.arange(100)
y = np.random.rand(len(x))
y_lower = y - 0.1
y_upper = y + 0.1
# a rasterized version with alpha
a['top'].fill_between(x, y_lower, y_upper, facecolor='yellow', alpha=0.5, rasterized=True)
# a rasterized whole axis, just for comparison
a['bottom'].set_rasterized(True)
a['bottom'].plot(x, y)
# save the figure, with the rasterized part at 300 dpi
f.savefig('testing.eps', dpi=300)
f.savefig('testing.png', dpi=300)
plt.close(f)
if __name__ == '__main__':
print plt.get_backend()
transparencytest()
The testing.png image looks like this:
The testing.eps image ends up looks like this (in converted pdf versions and the figure-rasterized png):
The black backgrounds behind the rasterized elements are not supposed to be there. How can I remove the black backgrounds when saving an eps figure with rasterized elements in it?
This has been tested with a bunch of other mpl backends, so it does not appear to be a specific problem with agg. Mac OS X 10.9.4, Python 2.7.8 built from MacPorts, Matplotlib 1.3.1.
This was a known bug which has been fixed.
This is due to the fact that eps does not know about transparency and the default background color for the rasterization was (0, 0, 0, 0) (black which is fully transparent).
I also had this problem (https://github.com/matplotlib/matplotlib/issues/2473) and it is fixed (https://github.com/matplotlib/matplotlib/pull/2479) in matplotlib 1.4.0 which was released last night.
I'm trying to use matplotlib to generate 3D figures where the xy plane is an image, and then some 3D tracks are drawn on top (that part works just fine). The problem is, even though my imported PNG shows just fine with imshow, and even though I can plot an image on a 3D axis if I just use an example from the cookbook, my image just shows up as a featureless black box. I'm sure I'm missing something small- thanks in advance!
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D, art3d
from pylab import ogrid
import matplotlib.pyplot as plt
plt.ioff()
fig = plt.figure()
ay=fig.add_subplot(2,1,1)
rawim=plt.imread(r'G:\Path\myimage.png')
ay.imshow(rawim,cmap='gray')
ax=fig.add_subplot(2,1,2,projection='3d')
x,y= ogrid[0:rawim.shape[0],0:rawim.shape[1]]
ax.plot_surface(x,y,0,rstride=5,cstride=5,facecolors=rawim,cmap='gray')
ax.view_init(elev=45, azim=12)
plt.show()
The output comes out as this (edited to include image).
PS Running Matplotlib 1.2.1 in Spyder for Python 2.75
Edited to add- I was largely modeling my approach from this post, so if instead of
rawim=plt.imread(r'G:\Path\myimage.png')
I use
from matplotlib.cbook import get_sample_data
fn = get_sample_data("lena.png", asfileobj=False)
rawim=read_png(fn)
it works perfectly. I've tried several of my PNG outputs, produced a couple of different ways, and no love. And yes, they're greyscale between 0-1.
You should use an explicit color array for facecolors.
You want something having shape (Nx, Ny, 4) where the "4" dimension holds RGBA values.
Also, get rid of the cmap='gray' in the plot_surface invocation.