I'm wanting to mimic the figure extents observed in an output figure and apply them to the figure object itself. The output figure command I want to copy is:
plt.savefig(flname, bbox_inches='tight', pad_inches=0.03)
I've been able to grab the bounding box which generates the observed bbox in the figure using:
bbox = fig.get_tightbbox(fig.canvas.get_renderer())
but am lost as to how to apply that to the fig object!
If you go here:
http://matplotlib.org/api/figure_api.html
And look under the Figure class constructor you will find that in add_axes() and gca() there is a way to set the bbox using one of the kwargs, clip_box.
Additionally here is more information about the bbox.
http://stackoverflow.com/questions/29809238/definition-of-matplotlib-pyplot-axes-bbox
I hope this helps you like it did for me. In short, you cannot apply it to a figure, but you can seem to apply it to all axes.
If I read this question correctly, it hasn't quite been answered by dozens of answers on this general topic elsewhere on stack overflow. The overwhelming focus there actually is on savefig output, rather than on the figure handle in memory. My application was also on the figure handle, and it worked easily enough like this:
# make figure. w,h and dpi optional but allow for exact figure sizing
hf = plt.plot(x,y,figsize=(w,h),dpi=myscreendpi)
# adjust padding as required
hf.set_tight_layout({'pad':0.5})
tightbbox = hf.get_tightbbox(hf.canvas.get_renderer())
# just set it directly to figure size
hf.set(figheight=tightbbox.height,figwidth=tightbbox.width)
Related
I have data that I would like to save as png's. I need to keep the exact pixel dimensions - I don't want any inter-pixel interpolation, smoothing, or up/down sizing, etc. I do want to use a colormap, though (and mayber some other features of matplotlib's imshow). As I see it there are a couple ways I could do this:
1) Manually roll my own colormapping. (I'd rather not do this)
2) Figure out how to make sure the pixel dimenensions of the image in the figure produced by imshow are exactly correct, and then extract just the image portion of the figure for saving.
3) Use some other method which will directly give me a color mapped array (i.e. my NxN grayscale array -> NxNx3 array, using one of matplotlibs colormaps). Then save it using another png save method such as scipy.misc.imsave.
How can I do one of the above? (Or another alternate)
My problem arose when I was just saving the figure directly using savefig, and realized that I couldn't zoom into details. Upscaling wouldn't solve the problem, since the blurring between pixels is exactly one of the things I'm looking for - and the pixel size has a physical meaning.
EDIT:
Example:
import numpy as np
import matplotlib.pyplot as plt
X,Y = np.meshgrid(np.arange(-50.0,50,.1), np.arange(-50.0,50,.1))
Z = np.abs(np.sin(2*np.pi*(X**2+Y**2)**.5))/(1+(X/20)**2+(Y/20)**2)
plt.imshow(Z,cmap='inferno', interpolation='nearest')
plt.savefig('colormapeg.png')
plt.show()
Note zooming in on the interactive figure gives you a very different view then trying to zoom in on the saved figure. I could up the resolution of the saved figure - but that has it's own problems. I really just need the resolution fixed.
It seems you are looking for plt.imsave().
In this case,
plt.imsave("filename.png", Z, cmap='inferno')
I have a series of straight line segments of varying thickness connected end-to-end to create meandering path. Does anyone know a way to paint this as a smooth meandering line, sort of like vectorizing it? I am using QPainter. I haven't had any success finding an appropriate function in QPainterPath.
The data looks something like this:
[(QPointF, width), (QPointF, width), (QPointF, width), ... ]
Thanks!
EDIT: Added example image
I wanted to leave it open to creative responses, but I am just looking to move from linear interpolation (QPainter::drawLine()) to spline interpolation.
If I understand your question correctly...
Don't draw a line, draw a filled polygon that encloses your line data with the right thickness. Drawback: That requires calculations on your data beforehand.
I'm trying to get and set the position of a draggable legend in matplotlib. My application consists of an interactive GUI, which has a redraw/plot function that should perform the follow steps:
save the position of the current legend.
clear the current axes and perform various plotting operations, which may or may add labels to their plots.
build a new draggable legend (ax.legend().draggable()) and restore the old position of the legend.
In between these steps the user is free to drag the legend around, and the goal is to persist the legend position when the plots are redrawn.
My first approach was to use oldpos = legend.get_bbox_to_anchor() and legend.set_bbox_to_anchor(oldpos) in steps 1 and 3. However this causes to move the legend completely off the visible area.
Note that I have to use ax.legend() and cannot use fig.legend(lines, labels), since step 2 is completely decoupled, i.e., I don't know anything about lines and labels in step 3. According to answers to the question How to position and align a matplotlib figure legend? there seems to be a difference between these two possibilities regarding axes or figure coordinates. Obviously my problem calls for figure coordinates, but I haven't fully understood how to convert the bbox to a "bbox in figure coordinates".
The even more severe problem I just realized is that apparently legend.get_bbox_to_anchor() always seems to return the same values irrespective of the drag position. So maybe the anchor can only be (ab-)used to manipulate the position of static legends? Is there another/proper way to save and restore the position of a draggable legend?
By looking at the implementation of Legend I found out that there is an undocumented property _loc, which exactly does what I want. My solution now looks astonishingly simple:
oldLegPos = ax.get_legend()._loc
# perform all plotting operations...
legend = ax.legend().draggable()
legend._loc = oldLegPos
It looks like _loc automatically stores figure coordinates, since I do not have to convert the coordinates in any way (eg. when the plotting operations completely change the axes ranges/coordinates).
This question already has an answer here:
Embed matplotlib figure in larger figure
(1 answer)
Closed 8 years ago.
How can I use a matplotlib Figure object as a subplot? Specifically, I have a function that creates a matplotlib Figure object, and I would like to include this as a subplot in another Figure.
In short, here's stripped-down pseudocode for what I've tried:
fig1 = plt.figure(1, facecolor='white')
figa = mySeparatePlottingFunc(...)
figb = mySeparatePlottingFunc(...)
figc = mySeparatePlottingFunc(...)
figd = mySeparatePlottingFunc(...)
fig1.add_subplot(411, figure=figa)
fig1.add_subplot(412, figure=figb)
fig1.add_subplot(413, figure=figc)
fig1.add_subplot(414, figure=figd)
fig1.show()
Sadly, however, this fails. I know for a fact the individual plots returned from the function invocations are viable--I did a figa.show(),...,figd.show() to confirm that they are OK. What I get for the final line in the above code block--fig1.show()--is
a collection of four empty plots that have frames and x- and y- tickmarks/labels.
I've done quite a bit of googling around, and experimented extensively, but it's clear that I've missed something that is either really subtle, or embarrassingly obvious (I'll be happy for it to be the latter as long as I can get un-stuck).
Thanks for any advice you can offer!
You can't put a figure in a figure.
You should modify your plotting functions to take axes objects as an argument.
I am also unclear why the kwarg figure is there, I think it is an artifact of the way that inheritance works, the way that the documentation is auto-generated, and the way some of the getter/setter work is automated. If you note, it says figure is undocumented in the Figure documentation, so it might not do what you want;). If you dig down a bit, what that kwarg really controls is the figure that the created axes is attached too, which is not what you want.
In general, moving existing axes/artists between figures is not easy, there are too many bits of internal plumbing that need to be re-connected. I think it can be done, but will involving touching the internals and there is no guarantee that it will work with future versions or that you will get warning if the internals change in a way that will break it.
You need to your plotting functions to take an Axes object as argument. You can use a pattern like:
def myPlotting(..., ax=None):
if ax is None:
# your existing figure generating code
ax = gca()
so if you pass in an Axes object it gets drawn to (the new functionality you need), but if you don't all of your old code will work as expected.
In GNU Octave you can make a picture where different colors represent different values in a matrix. You can also add a colorbar, which shows what color corresponds to what value.
Is it possible to somehow add units to the values shown in the colorbar? Instead of saying “0.36” it would say “0.36 V/nm”? I know this is possible in Matlab, but I can’t figure out how to do it in Octave. Any good workarounds?
I assume someone here will mention that I should use matplotlib instead (that usually happens). How would you accomplish the same thing with that?
The matplotlib answer (using pylab) is
imshow(random((20,20)))
colorbar(format='%.2f V/nm')
In Octave it seems that the following works (but I'm no Octave expert so maybe there's a better way):
c=colorbar();
labels = {};
for v=get(c,'ytick'), labels{end+1} = sprintf('%.2f V/nm',v); end
set(c,'yticklabel',labels);