Set the height and width of a mpld3 plot - matplotlib

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!

Related

PyQt application issue with matplotlib bar graph x ticks

I'm making a application to show graph using python pyqt5 and matplotlib.
here is a issue with graph I don't know why this happen.
You can see the 2 graph image I uploaded.
Second one is what I want to show.
But after show pie graph(There are so many types of graph I used in my application but only after pie graph happen this issue), it work like first image.
So, I wrote code after draw pie graph
self.MplWidget.canvas.axes.clear() like this.
But it doesn't change at all.
If I reboot my application it work well.
How I can show my graph like image2 after show pie graph?
this is my code to show bar graph
self.MplWidget.canvas.axes.bar(ind, graph1, width, label='price1' )
self.MplWidget.canvas.axes.bar(ind, graph2, width, bottom=graph1, yerr=Std, label='price2')
self.MplWidget.canvas.axes.title.set_text('graph1')
self.MplWidget.canvas.axes.set_xticks(ind)
self.MplWidget.canvas.axes.set_xticklabels(temp['date'], rotation=90 )
self.MplWidget.canvas.axes.legend(loc='best')
self.MplWidget.canvas.draw()
this is my code to show pie chart
self.MplWidget.canvas.axes.title.set_text('pie graph')
self.MplWidget.canvas.axes.pie(sizes, labels=labels, autopct='%1.1f%%',shadow=True, startangle=90)
self.MplWidget.canvas.axes.axis('equal')
self.MplWidget.canvas.draw()
self.MplWidget.canvas.axes.clear()
Axes.pie sets the aspect ratio of the axes to 'equal' which is what seems to mess up the bar plot. You could try setting self.MplWidget.canvas.axes.set_aspect('auto') when plotting the bar plot to reset the aspect ratio to 'auto'. You probably also want to set self.MplWidget.canvas.axes.set_frame_on(True) since Axes.pie removes the frame around the plot as well.
Another option could be to use separate widgets for each of the plots and combine them in a QStackedWidget or QTabWidget.

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-

How can I get and set the position of a draggable legend in 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).

Positioning figure and table in figure

I'm trying to put both a plot and a table in a figure, but I want some whitespace to separate the two. How do I position the table/plot at arbitrary positions? What I have now is the table of values showing up IMMEDIATELY under the x-axis (so that it's actually colliding into my axis labels...)
I don't know matplotlib at all...The documentation is not written very well either...
To position something in a figure you have to use the function set_position([left, bottom, width, height]). Example:
matplotlib.pyplot.axes().set_position([0.15, 0.20, 0.80, 0.70])