Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Bokeh to add interactivity to Python drawing

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to use Bokeh to add interaction to Python drawing", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Bokeh to add interactivity to Python drawing.

Drawing in Bokeh is a little more complex than some other drawing libraries, but the extra effort pays off. Bokeh is designed to allow you to create your own interactive drawings on Web while giving you detailed control over how interactivity works. I'll show this by adding tooltips to the multiple bars I've been using in this series. It draws data on the results of British elections between 1966 and 2020.

Make multiple bar graphs

Before we proceed, please note that you may need to adjust your Python environment to get this code running, including the following:

Run the latest version of Python (instructions on Linux, Mac, and Windows)

Make sure that the version of Python you are running works with these libraries.

The data is available online and can be imported using Pandas.

Import pandas as pddf = pd.read_csv ('https://anvil.works/blog/img/plotting-in-python/uk-election-results.csv')

Now we can move on.

In order to make multiple graphs, you need to adjust your data.

The raw data goes like this:

> print (long) year party seats0 1966 Conservative 2531 1970 Conservative 3302 Feb 1974 Conservative 2973 Oct 1974 Conservative 2774 1979 Conservative 339. ... 103 2005 Others 30104 2010 Others 29105 2015 Others 80106 2017 Others 59107 2019 Others 72 [60 rows x 3 columns]

You can think of the data as a series of seats values for each possible (year, party) combination. This is how Bokeh handles it. You need to make a list of (year, party) tuples:

# get the tuple of each possible (year, party) combination x = [(str (r [1] ['year']), r [1] [' party']) for r in df.iterrows ()] # This comes out as [('1922,' Conservative'), ('1923,' Conservative'),... ('2019,' Others')]]

These will be x values. The y value is the seat (seats).

Y = df ['seats']

Now your data should look like this:

X y ('1966,' Conservative') 253 ('1970,' Conservative') 330 ('Feb 1974,' Conservative') 297 ('Oct 1974,' Conservative') 277 ('1979,' Conservative') 339. 'Others') 30 (' 2010, 'Others') 29 (' 2015, 'Others') 80 (' 2017, 'Others') 59 (' 2019, 'Others') 72

Bokeh requires you to encapsulate the data in some of the objects it provides so that it can provide you with interactive functionality. Encapsulate your x and y data structures in a ColumnDataSource object.

From bokeh.models import ColumnDataSource source = ColumnDataSource (data= {"x": X, "y": y})

Then construct a Figure object and pass in the x data that you encapsulate in the FactorRange object.

From bokeh.plotting import figure from bokeh.models import FactorRange p = figure (x_range=FactorRange (* x), width=2000, title= "Election results")

You need to ask Bokeh to create a color table, which is a special DataSpec dictionary, which is generated based on the color mapping you give it. In this case, the color table is a simple mapping between a party name and a hexadecimal value.

From bokeh.transform import factor_cmap cmap = {'Conservative':' # 0343dfallows, 'Labour':' # e5000bands, 'Liberal':' # ffff14', 'Others':' # 929591cards,} fill_color = factor_cmap ('xmom, palette=list (cmap.values ()), factors=list (cmap.keys ()), start=1, end=2)

Now you can create a bar chart:

P.vbar (top='y', width=0.9, source=source, fill_color=fill_color, line_color=fill_color)

The visual form of the data on the Bokeh chart is called "glyph glyphs", so you have created a set of bar glyphs.

Adjust the details of the chart to make it look like you want it to be.

P.y_range.start = 0 p.x_range.range_padding = 0.1 p.yaxis.axis_label = 'Seats' p.xaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None

Finally, tell Bokeh that you want to see your drawings now:

From bokeh.io import show show (p)

This writes the drawing to a HTML file and opens it in the default Web browser. The results are as follows:

It already has some interactive features, such as box zooming.

But the great thing about Bokeh is that you can add your own interactivity. In the next section, we explore this problem by adding tooltips to the bar chart.

Add a tooltip to the bar chart

To add a tooltip to a bar chart, you just need to create a HoverTool object and add it to your drawing.

H = HoverTool (tooltips= [('Seats',' @ y'), ('(Year, Party)','(@ x)')]) p.add_tools (h)

Parameter defines which data is displayed on the tooltip. The variables @ y and @ x refer to the variables you passed into ColumnDataSource. You can also use some other values. For example, the position of the cursor on the graph is given by $x and $y (not related to @ x and @ y).

Here are the results:

With Bokeh's HTML output, you can get a complete interactive experience when embedding drawings into Web applications. You can copy this example here as an Anvil application (note: Anvil needs to be registered to use).

Now you can see the reasons for the extra effort to encapsulate all the data in Bokeh in objects such as ColumnDataSource. In return, you can add interactivity relatively easily.

At this point, I believe you have a deeper understanding of "how to use Bokeh to add interactivity to Python drawing". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report