How to use figure class in Bokeh

share link

by Dejaswarooba dot icon Updated: Sep 14, 2023

technology logo
technology logo

Solution Kit Solution Kit  

Bokeh is an interactive data visualization library in Python. Users utilize it to create highly interactive graphs and charts for web-based visualizations. It provides a wide range of visualization options.


It includes bar graphs, stacked bar charts, line graphs, and donut charts. Bokeh allows users to generate simple and multiple charts on a single plot. This makes it a powerful tool for visualizing complex datasets. By leveraging Python Bokeh, one can customize the visual appearance of plots. It includes axis labels, fill and line colors, and theme selection. The Bokeh library comes with interactive tools like hover tools and selection tools. These tools enhance the user experience.   


You can use it with Pandas DataFrames, NumPy, and Matplotlib. This facilitates data manipulation and preparation for visualization. Bokeh also enables users to create PNG format files and HTML files. You can view these in modern web browsers. The interactive features let you connect storylines, so different visuals work well together. Bokeh's user-friendly features make it an ideal choice for creating dynamic visualizations.  

Figure Class  

The `figure` method in Bokeh is a fundamental component of this powerful library. It is widely used for creating various interactive charts and highly engaging visualizations. It serves as the canvas on which users can plot their data. This enables them to generate a wide array of visualizations. It includes bar graphs, stacked bar charts, line graphs, and donut charts.  


Bokeh's `figure` method provides a flexible and intuitive interface. This allows us to create interactive plots with various plot models and annotations. You can customize them to enhance the visual appearance of the final visualization.  


Users can effortlessly add axis labels, tooltips, and interactive tools through this method. This enables the exploration of the data. Users can set plot dimensions in screen units. Users can also provide a specific hex value for the background theme. Once you have prepared the visualizations, you can export them as an HTML file. Web browsers can show them directly, using modern browser features for interactive parts. Bokeh supports multiple plots on the same canvas. This facilitates the exploration of complex relationships and comparisons between different datasets.  


To create a `figure` object, users can import necessary libraries. It includes Pandas and Numpy. Then, pass data from Pandas DataFrames or Python dictionaries to the Bokeh APIs. Various marker types and glyph methods are available. You can use them to add distinct visual elements to the plots. Bokeh's interactive legends make it easy to toggle different elements in the visualization. Bokeh's user guide and tutorials are useful for beginners to get started easily. That's why it's a go-to visualization library for everyone.  

Syntax  

figure([title], [x_axis_label], [y_axis_label], ...)  

Use square brackets to change the figure's appearance and what it can do. You can choose a title for the figure, label the X and Y axes, and customize other attributes.  

How to use figure class in Bokeh?

  • Start by installing Bokeh using the command `pip install bokeh`. After you install it, you can create interesting graphs and charts for web apps.  
  • To begin, import the required libraries, such as Pandas and NumPy. You can bring in important parts from Bokeh. Some examples are figure, output_file, show, gridplot, and HoverTool.  
  • Construct a basic plot by initializing a figure object. You can do this through the `figure()` function.  
  • We must also specify attributes like plot dimensions, title, and axis labels. For instance, you can create a simple line chart using NumPy-generated data.  
  • To enhance visual aesthetics, you can fine-tune attributes. This includes line color, fill color, and markers to distinguish data points.  
  • You use the `legend_label` argument for proper labeling.  
  • You can add annotations and interactivity. When you hover over plot points, the HoverTool shows data values as tooltips.  
  • When dealing with multiple plots, arrange them in a grid using `gridplot()`. You can also organize them as subplots.  
  • You can easily save and share your interactive visualization. One can use the `output_file()` and `show()` functions. These functions create an HTML file that contains your visualization. They display it in web browsers.   
  • You can export your plot to an HTML file and use the show function. This allows others to interact with your visualization.  


Preview of the output that you will get on running this code from your IDE

Code


p = figure(x_axis_type="datetime", width=800, height=350): Creates a new Bokeh figure with a datetime x-axis. It sets the width and height of the plot canvas.

import pandas as pd

from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, show, output_file

dic = {'2017-08-11': {'Yes': 157, 'Not sure': 2, 'No': 1}, '2017-08-22': {'Yes': 142, 'Not sure': 12}, '2017-08-01': {'Yes': 112, 'Others': 10, 'Not sure': 4, 'No': 9}, '2017-08-17': {'Yes': 117, 'No': 12, 'Not sure': 11, 'Others': 2}, '2017-08-25': {'Yes': 61, 'Not sure': 9}, '2017-08-23': {'Yes': 268, 'Not sure': 20, 'No': 1}, '2017-07-10': {'Yes': 123, 'Not sure': 4, 'No': 1}, '2017-08-10': {'Yes': 343, 'Not sure': 20}, '2017-07-13': {'Yes': 116, 'Others': 1, 'Not sure': 14, 'No': 2}, '2017-07-14': {'Yes': 255, 'Not sure': 22, 'No': 6}, '2017-08-07': {'Yes': 73, 'Others': 3, 'Not sure': 4, 'No': 5}, '2017-08-04': {'Not sure': 11, 'Others': 8, 'Yes': 178, 'No': 10}, '2017-08-16': {'Not sure': 10, 'Yes': 219}, '2017-07-18': {'Yes': 1, 'No': 1}, '2017-08-15': {'Yes': 301, 'Others': 4, 'Not sure': 37, 'No': 31}, '2017-08-08': {'Yes': 38, 'No': 2, 'Others': 1}, '2017-08-09': {'Yes': 120, 'Not sure': 3}, '2017-08-28': {'Yes': 206, 'Others': 2, 'Not sure': 18, 'No': 24}, '2017-08-14': {'Yes': 46, 'No': 3, 'Not sure': 5, 'Others': 7}}

df = pd.DataFrame.from_dict(dic, orient="index")
df = df.fillna(0)
df.index = pd.to_datetime(df.index)
df.index.name = 'Date'
df.sort_index(inplace=True)

df['Total'] = df.Yes + df['Not sure'] + df.No + df.Others
df['Precision'] = round(df.Yes/df.Total, 2)

source = ColumnDataSource(df)

p = figure(x_axis_type="datetime", plot_width=800, plot_height=350)
p.line('Date', 'Precision', source=source)

output_file("ts.html")
show(p)

Follow the steps carefully to get the output easily.

  • Download and install VS Code on your desktop.
  • Open VS Code and create a new file in the editor.
  • Copy the code snippet that you want to run, using the "Copy" button or by selecting the text and using the copy command (Ctrl+C on Windows/Linux or Cmd+C on Mac).,
  • Paste the code into your file in VS Code, and save the file with a meaningful name and the appropriate file extension for Python use (.py).file extension.
  • Install Bokeh using pip install bokeh
  • Open the folder in the code editor, copy and paste the above kandi code snippet in the Python file.
  • Replace the line
p = figure(x_axis_type="datetime", plot_width=800, plot_height=350)

with

p = figure(x_axis_type="datetime", width=800, height=350)
  • To run the code, open the file in VS Code and click the "Run" button in the top menu, or use the keyboard shortcut Ctrl+Alt+N (on Windows and Linux) or Cmd+Alt+N (on Mac). The output of your code will appear in the VS Code output console.


I hope you found this useful. I have added the link to dependent libraries, and version information in the following sections.


I found this code snippet by searching for "figure function bokeh" in Kandi. You can try any such use case!

Dependent Libraries


pandasby pandas-dev

Python doticonstar image 38689 doticonVersion:v2.0.2doticon
License: Permissive (BSD-3-Clause)

Flexible and powerful data analysis / manipulation library for Python, providing labeled data structures similar to R data.frame objects, statistical functions, and much more

Support
    Quality
      Security
        License
          Reuse

            pandasby pandas-dev

            Python doticon star image 38689 doticonVersion:v2.0.2doticon License: Permissive (BSD-3-Clause)

            Flexible and powerful data analysis / manipulation library for Python, providing labeled data structures similar to R data.frame objects, statistical functions, and much more
            Support
              Quality
                Security
                  License
                    Reuse

                      bokehby bokeh

                      Python doticonstar image 17667 doticonVersion:Currentdoticon
                      License: Permissive (BSD-3-Clause)

                      Interactive Data Visualization in the browser, from Python

                      Support
                        Quality
                          Security
                            License
                              Reuse

                                bokehby bokeh

                                Python doticon star image 17667 doticonVersion:Currentdoticon License: Permissive (BSD-3-Clause)

                                Interactive Data Visualization in the browser, from Python
                                Support
                                  Quality
                                    Security
                                      License
                                        Reuse

                                          If you do not have Bokeh or Pandas that is required to run this code, you can install it by clicking on the above link and copying the pip Install command from the page in kandi.


                                          You can search for any dependent library on kandi like Bokeh.

                                          Environment tested

                                          I tested this solution in the following versions. Be mindful of changes when working with other versions.


                                          1. The solution is created and tested using Vscode 1.77.2 version
                                          2. This code had been tested using python version 3.8.0
                                          3. Bokeh version 3.1.1 has been used.


                                          By using this technique, you can make attractive startup screens for GUI apps in Python's Tkinter. This process also facilitates an easy-to-use, hassle-free method to create a hands-on working version of code. This helps to use figure class of Bokeh in Python

                                          FAQ  

                                          1. What does Bokeh mean, and how can we use it to create Annotations?  

                                          Bokeh is a Python library for interactive data visualization. You can enhance your plots by adding labels, arrows, and shapes. This helps provide explanatory notes to the data and improves the visual context.  


                                          2. How do Bokeh graphs help make interactive graphs?  

                                          Bokeh makes interactive graphs with its tools. Users can hover over data points to see information and easily show or hide data series. They can also update plots based on user input.  


                                          3. What are the advantages of using Python Bokeh for data visualization?  

                                          Bokeh provides interactive, attractive data visualizations for web apps. The software has tools for interactive graphs and linked plots. It can easily work with modern browsers. This facilitates engaging and informative displays.  


                                          4. What types of plots does Python Bokeh support? 

                                          Python Bokeh can create various types of plots, like line charts, scatter plots, and bar charts. To visualize data differently, you can use histograms, area plots, and pie charts. This makes data visualization interactive and diverse. 

                                            

                                          5. How can I create a bar chart using Python Bokeh?  

                                          from Bokeh.plotting import figure, show  

                                          p = figure(x_range=["A", "B", "C"], plot_height=250)  

                                          p.vbar(x=["A", "B", "C"], top=[1, 2, 3], width=0.5)  

                                          show(p)  

                                          Support

                                          1. For any support on kandi solution kits, please use the chat
                                          2. For further learning resources, visit the Open Weaver Community learning page.

                                          See similar Kits and Libraries