How to customize the legends in Bokeh

share link

by gayathrimohan dot icon Updated: Aug 17, 2023

technology logo
technology logo

Solution Kit Solution Kit  

Bokeh is an open-source Python library. Web developers use it to create appealing and interactive visuals on web browsers. It is particularly useful for generating interactive plots, dashboards, and apps. This allows users to explore and understand data. Interactive controls like sliders, buttons, and tooltips do this. Bokeh supports various plot types, such as scatter plots, line charts, and bar charts. It is often used for creating data-driven web apps or embedding interactive visuals.   


In a chart created using this library in Python, we label the data known as bokeh legends.  

Types of legends used in Bokeh:  

  • Field Legends: These legends are created automatically when you use a "color," "size," "alpha," or other visual properties that vary with data in a glyph (like circles, lines, etc.). These legends provide information about the mapping of data values to visual attributes.  
  • Color Bars: Color bars are a type of legend used to display the mapping between data values and colors. Heatmaps or scatter plots use them where color represents a third variable.  
  • Legend Items: You can use the Legend object for more custom legends. Users use this legend object to create and position legend items. This is useful when adding non-standard labels or symbols to the legend.  
  • Grouping and Categorical Legends: Group and label different categories in your visualization.  
  • Custom Legends: Bokeh allows you to create customized legends by combining different elements. Those elements, like text labels, glyphs, and shapes, provide more context to your chart.  


You communicate the relationship between data and visuals in your plots and charts. Different types of bokeh legends help to accomplish this.  


It creates bokeh legends in the Bokeh library. This involves using a combination of attributes and methods. Legend items customize their appearance.  

 Some techniques include:  

  • Adding Legend Items: Use the Legend class to create a legend. Then add individual legend items using the add_item method. You can specify labels, glyphs, and other properties for each legend item.  
  • Setting Labels: You can set the labels for legend items by passing a list of strings to the labels' parameter. You can do this by calling the legend function. You can also assign labels to individual glyphs. When creating the glyphs, you can use the legend_label parameter to do this.  
  • Positioning the Legend: Control the legend's position by setting the parameter. When we call the legend function, we do this. Common options are "top_left", "top_right", "bottom_left", and "bottom_right".  
  • Customizing Appearance: Adjust the appearance of the legend by modifying attributes. The attributes are label_text_font, label_text_font_size, and label_text_color. Use CSS-style string values for these attributes.  
  • Hiding Legend Items: Set the visible attribute to False to hide specific legend items.  
  • Interactive Legends: To allow users to toggle the visibility of legend items. You can use the Toggle tool with the legend parameter.  
  • Grouping Legend Items: This can be useful for grouping similar legend items.  
  • Styling Legend Border and Background: Customize the legend's background by modifying attributes. like border_line_color, border_line_width, background_fill_color, and background_fill_alpha.  
  • Legend Click Policy: Specify how legend items should respond to clicks. Options include "hide" to toggle visibility. Options include "mute" to make other glyphs less opaque when clicking a legend item.  
  • Adding Legends to Layouts: Add the legend to your plot layout by passing it to the add_layout method.   


Here are some tips for capturing beautiful bokeh effects using the Bokeh library:  

  • Choose a Wide Aperture: To create a strong bokeh effect, use a lens with a wide aperture. This helps in achieving a shallow depth of field. That field makes the background blur more pronounced.  
  • Use a Telephoto Lens: This tends to create a more pronounced bokeh due to their longer focal lengths. This helps in isolating the subject and creating a creamy background blur.  
  • Get Close to the Subject: Closer distances enhance the bokeh effect. It will allow the subject to stand out from the background, resulting in a more prominent one.   
  • Choose a Simple Background: It helps emphasize the subject and the bokeh effect. Look for plain or distant backgrounds that won't distract from the focus.  
  • Select Interesting Light Sources: Lights in the background can turn into beautiful. Try capturing scenes with string lights, city lights, or sunlight filtering through leaves.  
  • Use Bokeh Shapes: The Bokeh library allows you to create custom shapes. Experiment with various shapes to add a creative touch to your images.  
  • Adjust Aperture Settings: Wider apertures (smaller f-numbers) produce more pronounced Bokeh.  
  • Focus on a Single Subject: To make your subject stand out, focus on a single point. The point is which will render the other elements in the frame with the bokeh effect.  
  • Experiment with Bokeh Filters: Experiment with these filters to create unique visuals.  


In conclusion, the bokeh legend technique, coupled with the bokeh library. This library offers a distinct way to enhance data visualization. Bokeh's interactive, web-based approach allows for the dynamic exploration of visualizations. To present complex data effectively, we make it particularly suitable. The bokeh legend technique enables the customization of legends. Improving the clarity and aesthetics of plots accomplishes this. This combination empowers users to create engaging and informative visuals. Specific needs use that. Making the bokeh legend technique and library valuable assets of data visual is what we do.  

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


In this solution we are using Bokeh library of Python.


Follow the steps carefully to get the output easily.

  1. Download and Install the PyCharm Community Edition on your computer.
  2. Open the terminal and install the required libraries with the following commands.
  3. Install pandas - pip install pandas.
  4. Install bokeh - pip install bokeh.
  5. Create a new Python file on your IDE.
  6. Copy the snippet using the 'copy' button and paste it into your Python file.
  7. Run the current file to generate the output.

I hope you found this useful.

I found this code snippet by searching for 'Bokeh-legend outside the plot' in Kandi. You can try any such use case!

Environment Tested

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

  1. PyCharm Community Edition 2022.3.1
  2. The solution is created in Python 3.11.1 Version
  3. pandas v2.0.2 Version
  4. bokeh v2.4.3 Version

Using this solution, we can able to customize the legends in Bokeh in Python with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to customize the legends in Bokeh in Python.

Dependent libraries

bokehby bokeh

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

Interactive Data Visualization in the browser, from Python


            bokehby bokeh

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

            Interactive Data Visualization in the browser, from Python

                      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


                                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

                                          You can search for any dependent library on 'pandas' and 'bokeh'.


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


                                          1. What is Bokeh - Annotations, and what can it do for visualizing data?  

                                          Bokeh Annotations refer to the ability of the Bokeh library. You can use it to add explanatory labels, arrows, and shapes to your plots. Annotations help you provide more context for your data visualizations. By making them more informative and easier to understand, we do this. You can use Bokeh Annotations to emphasize important features in your plots. This feature enhances the clarity and communicative power of your visualization. You can convey insights from your data to your audience.   


                                          2. How do you add a line legend to your plot using Bokeh?  

                                          You can use the Legend class to add a legend to your plot using Bokeh. To do it, use "figure" and "show" from the "bokeh.plotting" library and "Legend" from "bokeh.models". 


                                          # Create a figure p = figure ()  

                                          # Add some glyphs (lines, circles, etc.) to the plot line1 = p.line(x=[1, 2, 3], y=[4, 5, 6], line_color="blue", line_width=2, legend_label="Line 1") line2 = p.line(x=[1, 2, 3], y=[6, 5, 4], line_color="red", line_width=2, legend_label="Line 2")  

                                          # Create a legend legend = Legend (items= [ ("Line 1", [line1]), ("Line 2", [line2]),])  

                                          # Add the legend to the plot p.add_layout(legend, 'right')  


                                          In this example, use the Legend class to create a legend showing the plot (p). The add_layout method is also used to add a legend to the plot. You use the legend_label parameter to specify the label in the legend for each glyph. Adjust the positioning of the legend using the second argument of the add_layout function (e.g., 'right', 'top_left', etc.). You can also customize the appearance of the legend. The Legend class uses various attributes and properties to do this.  


                                          3. What are the advantages of creating a bar plot with Bokeh instead of other plotting tools?  

                                          Creating a bar plot with Bokeh offers several advantages over other plotting tools:  

                                          • Interactive Visualizations: Bokeh provides interactive features. Those features allow users to zoom, pan, and hover over data points on the plot.   
                                          • Bokeh generates plots that developers can embed in web applications. Enabling easy sharing and integration with web interfaces does this.  
                                          • Cross-Platform Compatibility: Bokeh supports various platforms and browsers. You can do this without needing to install any additional plugins or software.  
                                          • Pythonic Syntax: It integrates with the Python ecosystem. Data scientists and analysts make it convenient.   
                                          • Streaming Data: Bokeh supports real-time streaming of data. It needs to be suitable for certain applications to make the plot update dynamically.  
                                          • Customization and Theming: Bokeh offers a wide range of customization options. This allows you to style plots according to your needs. You enhance the visual appeal of your visualizations. 


                                          4. Is it possible to use Pandas DataFrames within Bokeh Legends?  

                                          Bokeh supports using Pandas DataFrames within legends. But you can create legends in Bokeh using glyph names and labels. You can achieve your aim by converting the DataFrame into a format.   


                                          5. What are the best practices for creating many plots with Bokeh Legends?  

                                          When creating many plots with Bokeh legends, consider these best practices:  

                                          • Consistent Naming: Give each glyph a meaningful name using the legend_label parameter. Ensure that the names are consistent across different plots for accurate legend grouping.  
                                          • Common Legend: Create a single legend if plots share the same data source and attributes. You can specify the legend parameter in one plot to do this. Other plots will inherit the legend.  
                                          • Explicit Legend Creation: You can customize the location, orientation, and other legend properties.  
                                          • Location and Orientation: Consider the plot layout and visual balance. Adjust the orientation using legend.orientation.  
                                          • Customize legend labels using HTML to improve the readability of legend labels. This is especially useful when including special characters, subscripts, or superscripts.  
                                          • Legend Click Policy: Specify how legends interact with plots. You use the legend.click_policy property to do this. When you click on legend items, you can use options like "hide" or "mute" to control the behavior of glyphs.  
                                          • Interactive Legends: This can provide an interactive experience to users.  
                                          • Avoid Overcrowding: Consider using separate legends or grouping items.  
                                          • Hover Tool Integration: Integrate the Hover Tool with the legend to enhance interactivity.   
                                          • Testing and Adjusting: Test your plots with legends and adjust their properties. To achieve the desired appearance and functionality, we do this. Keep user experience in mind.  

                                          See similar Kits and Libraries