How can I get and set the position of a draggable legend in matplotlib - matplotlib

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

Related

How do I save color mapped array of same dimensions of the original array?

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

How to control the specific size of plot in matplotlib?

Let us suppose that I am plotting a few plots with pyplot/matplotlib. Now, the first has to have tick marks and tick labels, and only the first. The last has to have a colorbar and some marks for scale. If I do a script specifying the figure size, the plot proper in the last and first plots is drawn with smaller sizes, as the figure has to make room for the extra markings. And I seem to be not able to control that, in an automatic way, like making the other plots at the same scale inside a larger figure or something like that.
Example code (it looks a little non-pythonic because I am using PyPlot inside Julia):
using PyPlot
SomeData=randn(64,64,3)
for t=1:3
figure(figsize=(3.0,3.0))
imagen=imshow(SomeData[:,:,t], origin="lower")
if t!=3
xticks([])
yticks([])
else
tick_params(labelsize=8, direction="out")
end
if t==1
cbx=colorbar(imagen, fraction=0.045, ticks=[])
cbx[:set_label]("Some proper English Label", fontsize=8)
end
savefig("CSD-$t.svg",dpi=92)
end
Thanks in advance-

Matplotlib's Figure and Axes explanation

I am really pretty new to matplotlib, though I know that it can be very powerful.
I've been reading number of tutorials and examples and it's a real hassle to understand how does matplotlib's Figure and Axes work. I am illustrating, what I am trying to understand, with the attached figure.
I know how to create a figure instance of certain size in inches. However, what bothers me is how can I create subplots and then axes, within each subplot, with relative coordinates (bottom=0,left=0,top=1,right=1) as illustrated.
So, for example I want to create a "parent" plot area (say (6in,10in)). Then, I want to create two subplot areas, each with size (3in,3in), with 1in space from the top, 2in space between the two vertical subplot areas and 1in from bottom. Then, 1in space on the left and 2in space on the write. In the same time, I would like to be able to get the coordinates of the subplot areas with respect to the main plot area.
Then, inside the first subplot area, I'd like to create 2 axis instances, with Axis 1, having coordinates with respect to Subplot Area1 (0.1,0.7,0.7,0.2) and Axes 2 (0.1,0.2,0.7,0.5). And then of course I'd like to be able to plot on these axes e.g., ax1.plot()....
If you could provide a sample code to achieve that, then I can study it.
Your help will be very much appreciated!
a subplot and an Axes object are really the same thing. There is not really a "subplot" as you describe it in matplotlib. You can just create your three Axes objects using gridspec without the need to put them in your "subplots".
There are a few different ways to create Axes instances within your figure.
fig.add_axes will create an Axes instance at the position given to it (you give it [left,bottom,width,height] in figure coordinates (i.e. 0,0 is bottom left, 1,1 is top right).
fig.add_subplot will also create an Axes instance. In this case, rather than giving it a rectangle to be created in, you give it the number of rows and columns of subplots you would like, and then the plot_number, where plot_number starts at 1, increments across rows first and has a maximum of nrows * ncols.
For example, to create the top-left Axes in a grid of 2 row and 2 columns, you could do the following:
fig.add_subplot(2,2,1)
or the shorthand
fig.add_subplot(221)
There are some more customisable ways to create Axes as well, for example gridspec and subplot2grid which allow for easy creation of many subplots of different shapes and sizes.

Seaborn Heatmap Colorbar Location

The cbar_kws argument of seaborn.heatmap accepts the parameters that fig.colobar accepts.
Is there a way to adjust the placement of the colorbar, simply to adjust the location to the left (especially when the correlation matrix is adjusted to have only a lower triangle).
I can adjust the labels by overriding the tick labels. As of now I still have to adjust the upper-right borders in post-processing, but it would make things much easier if I didn't have to edit the color bar as well.
heatmap accepts a cbar_ax argument; if you want to specify the position of the colorbar, the best thing to do is to set up the figure how you want it and then pass the specific axes.
You can also move axes around after plotting through normal matplotlib commands.

Set the height and width of a mpld3 plot

I want to set the width and height of a mpld3 plot to a specific value (in pixels, so it fits the div it is in). The way I tried it looks like this (javascript):
commands["width"]=plotWidth;
commands["height"]=plotHeight;
mpld3.draw_figure("plotname",commands);
plotWidth and plotHeight the values I want the height and width to be set to.
Now, this actually sets the size of the mpld3-figure object to the values I want, but the plot inside still keeps its old size, so it looks like nothing happened.
So, how do I change the size of the plot itself? So far it looks like whatever I do, the plot does not change.
You can change the shape of an mpld3 plot when creating a figure with the python code plt.figure(figsize=(width,height)) (where width and height are in inches). Here is a notebook demonstrating this.
There has been some interest in making mpld3 figures "responsive", which would be a cooler and more precise way to accomplish your goal, but so far no one has tried making the necessary code changes. Patches welcome!