How to keep visualizations (i.e. draw('mpl')) displayed while other code is called - matplotlib

I would like to be able to save and call a visualization, then have it show in-between other code. I know with MatPlotLib, you can do plt.show(), is there anything like that for Qiskit?
def test():
return plot_bloch_multivector(circ)
print("This is what the plot looks like")
test()
print("See? Anyway...")
# more code
Output:
This is what the plot looks like
See? Anyway...
Desired output:
This is what the plot looks like
# O O O (displayed bloch multivector)
See? Anyway...
I am using Google Colab (ver. 3.7.15).

In any jupyter notebook (including Google Colab), you can display an object with display
def test():
return plot_bloch_multivector(circ)
print("This is what the plot looks like")
display(test()) # <----------------------
print("See? Anyway...")

Related

What wizardry is being used to display Matplotlib color maps in an ipython console?

I am working with Matplotlib color maps, and I also happen to be working with the Spyder IDE, which has an ipython console.
As you can see from the screen shot, the ipython console showed me a graphical representation of the color map object. This was unexpected and very helpful.
Normally I expect to see a string representation of an object, as you might see from the print() function call. Function calls to print() and repr() are shown, and they produce text, as is more typical.
I would like my own code to output this graphical representation when it is generating output. I have been poking through the matplotlib.colors.Colormap internals, and so far I haven't been able to figure out how. What is ipython doing? How can I do the same?
Thanks!
This rather seems like a ipython/jupyter feature. ipython detects the object and produces automatically a plot to preview the colormap.
Here using jupyter:
IPython looks if an object has a _repr_html_; if so, it calls it and displays the output as HTML. Here's an example (I ran this in Jupyter but it works the same as long as you're running IPython):
class MyCoolObject:
def _repr_html_(self):
return ("<h1>hello!</h1> <p>this is some html </p>"
"I can even put images:"
"<img src='https://upload.wikimedia.org/wikipedia"
"/commons/thumb/3/38/Jupyter_logo.svg"
"/44px-Jupyter_logo.svg.png'></img>")
MyCoolObject()
To add on to Eduardo's answer, from everything I've read adding a _repr_html_ method should make iPython display the object when you type it into the console. I also use spyder though, and could not get it to work the way I expected. This simple wrapper class should allow you to display any html:
class displayedHTML:
def __init__(self, html):
self.html = html
def _repr_html_(self):
return self.html
But as you can see it does not work for me, instead showing the (implicitly defined) __repr__ of the class.
In [2]: obj = displayedHTML("<h1>" + "hello world" + "</h1>")
In [3]: obj
Out[3]: <__main__.displayedHTML at 0x1e8cda8f0d0>
I was not able to find the reason why this does not work, but I found a workaround if you just want to display a matplotlib colormap in the console from code (like I did).
Since know the matplotlib object works correctly, we can just give it to the ipython display function:
from IPython.display import display #Included without import since IPython 5.4 and 6.1
viridis = matplotlib.cm.get_cmap('viridis')
display(viridis)
And for me this works...
not_allowed_to_insert_pictures_yet.jpg
Hope this helps!

How to cache a plot in streamlit?

I have built a dashboard in streamlit where you can select a client_ID and have SHAP plots displayed (Waterfall and Force plot) to interpret the prediction of credit default for this client.
I also want to display a SHAP summary plot with the whole train dataset. The later does not change every time you make a new prediction, and takes a lot of time to plot, so I want to cache it. I guess the best approach would be to use st.cache but I have not been able to make it.
Here below is the code I have unsuccessfully tried in main.py:
I first define the function of which I want to cache the output (fig), then I execute the output in st.pyplot. It works without the st.cache decorator, but as soon as I add it and rerun the app, the function summary_plot_all runs indefinitely
IN:
#st.cache
def summary_plot_all():
fig, axes = plt.subplots(nrows=1, ncols=1)
shap.summary_plot(shapvs[1], prep_train.iloc[:, :-1].values,
prep_train.columns, max_display=50)
return fig
st.pyplot(summary_plot_all())
OUT (displayed in streamlit app)
Running summary_plot_all().
Does anyone know what's wrong or a better way of caching a plot in streamlit ?
version of packages:
streamlit==0.84.1,
matplotlib==3.4.2,
shap==0.39.0
Try
import matplotlib
#st.cache(hash_funcs={matplotlib.figure.Figure: lambda _: None})
def summary_plot_all():
fig, axes = plt.subplots(nrows=1, ncols=1)
shap.summary_plot(shapvs[1], prep_train.iloc[:, :-1].values,
prep_train.columns, max_display=50)
return fig
Check this streamlit github issue

Using ggplot2 with Julia pluto notebook

I am working with a Pluto.jl notebook. I would like to use the ggplot2 R library to make some plots.
Following this example, if I run the following code in the Julia REPL then I can get a ggplot2 graph output.
using RCall
#rlibrary ggplot2
using DataFrames
df = DataFrame(v = [3,4,5], w = [5,6,7], x = [1,2,3], y = [4,5,6], z = [1,1,2])
ggplot(df, aes(x=:x,y=:y)) + geom_line()
Now, when I use the same code in a pluto.jl notebook (with each line being a separate cell), then I get the following error message:
Is there a way to get the ggplot2 image to appear inside the pluto notebook?
Similarly, if I just enter ggplot() into a cell, I get the same error, but ggplot not defined.
With #library Pluto.jl seems to be unable to find the R package.
However Pluto can handle this format:
#rimport ggplot2 as ggplot2
I managed to see the picture after clicking the "play" button 3 or 4 times. That is the end of good news - the Plut-RCall integration is kind of unstable. The graph shows in a separate Window that seems to hang - this is perhaps a story for opening an issue.
However what you can try to do is to save the image to a file and than visualize it:
begin
ggplot2.ggplot(df, ggplot2.aes(x=:x, y=:y)) + ggplot2.geom_line()
ggplot2.ggsave("myplot.png")
im1 = Images.load("myplot.png")
end
As a workaround, it is possible to override Base.show manually (see Pluto.jl/sample/test1.jl) with
function Base.show(io::IO, ::MIME"image/png", p::RObject{VecSxp})
(path, _) = mktemp()
R"ggsave($path, plot=$p, device = 'png')"
im = read(path)
rm(path)
write(io, im)
end
After that, cells which output anything of the type RObject{VecSxp} will show a PNG image:

Graphvis output is not shown in Colab

Colab is not showing the output of a Graphviz plot (for example https://graphviz.readthedocs.io/en/stable/examples.html). How can I achieve it simply in Colab? I even tried to plot it's generated PDF file but it's not straightforward.
You don't need to call g.view(). Just end the code with g is enough, like this:
g = Digraph('G')
g.edge('Hello', 'World')
g
Here's a minimal example notebook

Interactive image plotting with matplotlib

I am transitioning from Matlab to NumPy/matplotlib. A feature in matplotlib that seems to be lacking is interactive plotting. Zooming and panning is useful, but a frequent use case for me is this:
I plot a grayscale image using imshow() (both Matlab and matplotlib do well at this). In the figure that comes up, I'd like to pinpoint a certain pixel (its x and y coordinates) and get its value.
This is easy to do in the Matlab figure, but is there a way to do this in matplotlib?
This appears to be close, but doesn't seem to be meant for images.
custom event handlers are what you are going to need for this. It's not hard, but it's not "it just works" either.
This question seems pretty close to what you are after. If you need any clarification, I'd be happy to add more info.
I'm sure you have managed to do this already. Slightly(!) modifying the link, I've written the following code that gives you the x and y coordinates once clicked within the drawing area.
from pylab import *
import sys
from numpy import *
from matplotlib import pyplot
class Test:
def __init__(self, x, y):
self.x = x
self.y = y
def __call__(self,event):
if event.inaxes:
print("Inside drawing area!")
print("x: ", event.x)
print("y: ", event.y)
else:
print("Outside drawing area!")
if __name__ == '__main__':
x = range(10)
y = range(10)
fig = pyplot.figure("Test Interactive")
pyplot.scatter(x,y)
test = Test(x,y)
connect('button_press_event',test)
pyplot.show()
Additionally, this should make it easier to understand the basics of interactive plotting than the one provided in the cookbook link.
P.S.: This program would provide the exact pixel location. The value at that location should give us the grayscale value of respective pixel.
Also the following could help:
http://matplotlib.sourceforge.net/users/image_tutorial.html