How to save a bokeh gridplot as single file - python

I am using bokeh (0.8.1) in combination with the ipython notebook to generate GridPlots. I would like to automatically store the generated GridPlots to a single png (hopefully pdf one day) on disk, but when using "Preview/Save" it cycles through all of the figures asking me to store them separately. Is there a more efficient way?

You can export plot layouts in the same manner that you can export individual plots:
from bokeh.io import export_png
from bokeh.layouts import gridplot
plots = gridplot([[plot_1, plot_2], [plot_3, plot_4]])
export_png(plots, filename='./path/to/file.png')
Note that there are additional dependencies per bokeh documentation:
The selenium python library
A headless browser and driver (eg chromium and chromedriver)

First you save your grid in an object,
Let's say "a" the you confirms that "a" is a grid. Example
grid = bly.gridplot(graficas,ncols=3) # Here you save your grid
bpl.show(grid). # Here you show your grid
from bokeh.io import export_png # You need this library to export
Exportar grid
export_png(grid, filename="your path/name.png")

Related

How best to create a simple, interactive, shareable plot with python?

I'm hoping someone can point me in the right direction. The python datavis landscape has now become huge and there are so many options that I'm a bit lost on what the best way to achieve this is.
I have an xarray dataset (but it could easily be a pandas dataframe or a list of numpy arrays).
I have 3 columns, A, B, and C. They contain 40 data points.
I want to plot a scatter plot of A vs B + scale*C where scale is determined from an interactive slider.
The more advanced version of this would have a dropdown where you can select a different set of 3 columns but I'll worry about that bit later.
The caveat on all of this is that I'd like it to be online and interactive for others to use.
There seem to be so many options:
Jupyter (I don't use notebooks so I'm not that familiar with them but
with mybinder I assume this is easy to do)
Plotly
Bokeh Server
pyviz.org (this is the really interesting one but again, there'd seem
to be so many options on how to accomplish this)
Any thoughts or advice would be much appreciated.
There are indeed many options and i'm not sure what is best but i use bokeh a lot and am happy about it. The example below can get you started. To launch this open a cmd in the directory where you save the script and run "bokeh serve script.py --show --allow-websocket-origin=*".
from bokeh.plotting import figure
from bokeh.io import curdoc
from bokeh.models.widgets import Slider
from bokeh.models import Row,ColumnDataSource
#create the starting data
x=[0,1,2,3,4,5,6,7,8]
y_noise=[1,2,2.5,3,3.5,6,5,7,8]
slope=1 #set the starting value of the slope
intercept=0 #set the line to go through 0, you can change this later
y= [slope*i + intercept for i in x]#create the y data via a list comprehension
# create a plot
fig=figure() #create a figure
source=ColumnDataSource(dict(x=x, y=y)) #the data destined for the figure
fig.circle(x,y_noise)#add some datapoints to the plot
fig.line('x','y',source=source,color='red')#add a line to the figure
#create a slider and update the graph source data when it changes
def updateSlope(attrname, old, new):
print(str(new)+" is the new slider value")
y = [float(new)*i + intercept for i in x]
source.data = dict(x=x, y=y)
slider = Slider(title="slope", value=slope, start=0.0, end=2.0,step=0.1)
slider.on_change('value', updateSlope)
layout=Row(fig,slider)#put figure and slider next to eachother
curdoc().add_root(layout)#serve it via "bokeh serve slider.py --show --allow-websocket-origin=*"
The allow-websocket-origin=* is to allow other users to reach out to the server and see the graph. The http would be http://yourPCservername:5006/ (5006 is the default bokeh port). If you don't want to serve from your PC you can subscribe to a cloud service like Heroku: example.

Bokeh and how to make it into a GUI

I am writing in python and have all my functionalities for analyzing datasets. Now, I would like to turn these functions into a user-ready application that, in a sense, works like an .exe app. In bokeh, I saw that you could create a plot, table...etc; however, is it possible to create a GUI where you can:
upload a file for analysis
load functions from my written python to analyze the uploaded file
graph the results onto a graph
click different buttons that can take you to different (so-called) pages so that you can perform different functions.
basically it can go from one page to the other kind of like a webpage where you click one button it links you to the next page for another purpose and home to go back. Could you potentially do this with bokeh?
There are several examples of data web applications created using Bokeh at demo.bokeh.org. Here is one modeled after the "Shiny Movie Explorer", but written in pure Python/Bokeh (instead of R/Shiny).
You can find much more details about creating and deploying Bokeh applications in the Running a Bokeh Server chapter of the docs.
Here is a complete (but simpler) example that demonstrates the basic gist and structure:
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Slider
from bokeh.plotting import figure
# Set up data
x = np.linspace(0, 4*np.pi, 200)
y = np.sin(x)
source = ColumnDataSource(data=dict(x=x, y=y))
# Set up plot
plot = figure(title="my sine wave")
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
# Set up widgets
freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1, step=0.1)
# Set up callbacks
def update_data(attrname, old, new):
# Get the current slider values and set new data
k = freq.value
x = np.linspace(0, 4*np.pi, 200)
y = np.sin(k*x)
source.data = dict(x=x, y=y)
freq.on_change('value', update_data)
# Set up layouts and add to document
curdoc().add_root(column(freq, plot))
curdoc().title = "Sliders"
To run this locally you'd execute:
bokeh serve --show myscript.py
For more sophisticated deployments (i.e. with proxies) or to embed directly in e.g. Flask, see the docs.

Precompute Jupyter widget results and embed in HTML

I'm currently working on a Jupyter notebook that creates an energy level diagram using matplotlib. One parameter of the underlaying spectrum computation can be varied using an interact statement. Now I want to export this notebook to HTML while the widget functionality should stay intact. Is it possible to precompute all possible outcomes and include them into the HTML version? Users should be able to use the interact feature without having to connect to a kernel.
Thanks for advice.
Peter
EDIT: I hope to clarify my question with the following sample code:
from ipywidgets import interact
import matplotlib.pyplot as plt
import numpy as np
def f(a):
x = np.linspace(0,2,100)
plt.plot(x,a*x**2)
plt.ylim([0,20])
plt.show()
return None
interact(f, a=(1,5,1))
In the final HTML file all possible images (in this case all parabolas with a=1...5) should be included (in this sense pre-computed) and then displayed when the user selects the appropiate value with the slider.

python matplotlib save graph as data file

I want to create a python script that zooms in and out of matplotlib graphs along the horizontal axis. My plot is a set of horizontal bar graphs.
I also want to make that able to take any generic matplotlib graph.
I do not want to just load an image and zoom into that, I want to zoom into the graph along the horizontal axis. (I know how to do this)
Is there some way I can save and load a created graph as a data file or is there an object I can save and load later?
(typically, I would be creating my graph and then displaying it with the matplotlib plt.show, but the graph creation takes time and I do not want to recreate the graph every time I want to display it)
You can use pickle package for saving your axes and then load it back.
Save your plot into a pickle file:
import pickle
import matplotlib.pyplot as plt
ax = plt.plot([1,2,5,10])
pickle.dump(ax, open("plot.pickle", "wb"))
And then load it back:
import pickle
import matplotlib.pyplot as plt
ax = pickle.load(open("plot.pickle", "rb"))
plt.show()
#Cedric's Answer.
Additionally, if you get the pickle error for pickling functions, add the 'dill' library to your pickling script. You just need to import it at the start, it will do the rest.

Export SVG out of matplotlib-venn

I have started to use matplotlib-venn for plotting venn diagram. It's a very useful tool, but I would like to know whether the graph generated can be saved in an SVG (or even pdf) format. I want to keep the graph vector, not rasterize it as in png.
I think there is a way, so if you can point me to it, that would be very helpful.
You can use the standard savefig method. Just give your output path a '.svg' extension:
from matplotlib_venn import venn2
import matplotlib.pyplot as plt
venn2(subsets = (3, 2, 1))
plt.savefig('venn2.svg')
You can save to PNG with a .png extension and... you can probably see where this is going for other formats.
Looks like you need to configure the SVG 'backend':
The matplotlib frontend or matplotlib API is the set of classes that
do the heavy lifting, creating and managing figures, text, lines,
plots and so on (Artist tutorial). This is an abstract interface that
knows nothing about output. The backends are device-dependent drawing
devices, aka renderers, that transform the frontend representation to
hardcopy or a display device (What is a backend?). Example backends:
PS creates PostScript® hardcopy, SVG creates Scalable Vector Graphics
hardcopy,...
> # The default backend; one of GTK GTKAgg GTKCairo GTK3Agg GTK3Cairo
> # CocoaAgg MacOSX Qt4Agg Qt5Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG
> # Template.
> # You can also deploy your own backend outside of matplotlib by
> # referring to the module name (which must be in the PYTHONPATH) as
> # 'module://my_backend'. backend : qt4agg
Src: http://matplotlib.org/Matplotlib.pdf

Categories

Resources