Python Bokeh - Visualizing the Iris Dataset

Python Bokeh - Visualizing the Iris Dataset

Bokeh is a powerful interactive visualization library in Python. Here's how you can use Bokeh to visualize the famous Iris dataset:

First, make sure you have Bokeh installed. If not, you can install it via pip:

pip install bokeh 

Next, you can use the following script to visualize the Iris dataset using Bokeh:

from bokeh.plotting import figure, show, output_file from bokeh.models import ColumnDataSource, CategoricalColorMapper from bokeh.palettes import Spectral3 from sklearn.datasets import load_iris # Load the Iris dataset iris = load_iris() flowers = iris.data feature_names = iris.feature_names species = [iris.target_names[i] for i in iris.target] # Convert to a ColumnDataSource source = ColumnDataSource(data={ feature_names[0]: flowers[:, 0], # sepal length feature_names[1]: flowers[:, 1], # sepal width feature_names[2]: flowers[:, 2], # petal length feature_names[3]: flowers[:, 3], # petal width 'species': species, }) # Create color map color_mapper = CategoricalColorMapper(factors=iris.target_names, palette=Spectral3) # Create a scatter plot p = figure(title="Iris Morphology", x_axis_label=feature_names[0], y_axis_label=feature_names[2]) p.scatter(x=feature_names[0], y=feature_names[2], source=source, color={'field': 'species', 'transform': color_mapper}, legend_field='species') # Move the legend outside the plot area p.legend.location = 'top_left' p.legend.title = 'Species' # Save the plot to a file output_file("iris.html") show(p) 

This script does the following:

  1. Loads the Iris dataset using sklearn.datasets.load_iris.
  2. Sets up a ColumnDataSource which is the Bokeh's object for storing and managing data.
  3. Creates a CategoricalColorMapper to color the different species in the dataset.
  4. Creates a scatter plot visualizing petal length against sepal length.
  5. Customizes the plot by setting the title, axis labels, and adding a legend.
  6. Outputs the visualization to an HTML file and opens it in a web browser.

This script assumes you want to compare petal length and sepal length. You can adjust the x and y parameters in the p.scatter function call to compare different features.

When you run this script, Bokeh will generate an HTML file and open a new tab in your default web browser to display the plot.


More Tags

netsh plink lambda tvos group-policy pipe tidyverse ora-06512 ts-node string-formatting

More Programming Guides

Other Guides

More Programming Examples