I have the following code:
from bokeh.plotting import figure, show, output_file
from bokeh.sampledata.iris import flowers
colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'}
colors = [colormap[x] for x in flowers['species']]
p = figure(title = "Iris Morphology")
p.xaxis.axis_label = 'Petal Length'
p.yaxis.axis_label = 'Petal Width'
p.circle(flowers["petal_length"], flowers["petal_width"],
color=colors, fill_alpha=0.2, size=10)
output_file("iris.html", title="iris.py example")
show(p)
Which produces this plot
How can I add legend based on the color of the circle to the plot? Where:
Legends added to Bokeh plots can be made interactive so that clicking or tapping on the legend entries will hide or mute the corresponding glyph in a plot. These modes are activated by setting the click_policy property on a Legend to either "hide" or "mute" .
The easiest way that comes to mind is to define a ColumnDataSource to your plot to which you pass your data and from there reference the column with the "species"
data from your dataframe.
Here is your code rework using this solution:
from bokeh.plotting import ColumnDataSource, figure, show, output_file
from bokeh.sampledata.iris import flowers
from bokeh.plotting import (ColumnDataSource, figure, show, output_file)
from bokeh.sampledata.iris import flowers
colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'}
colors = [colormap[x] for x in flowers['species']]
flowers['colors'] = colors
source = ColumnDataSource(flowers)
p = figure(title = "Iris Morphology")
p.xaxis.axis_label = 'Petal Length'
p.yaxis.axis_label = 'Petal Width'
p.circle("petal_length", "petal_width",
color='colors', fill_alpha=0.2, size=10, legend='species',source=source)
p.legend.location = "top_left"
output_file("iris.html", title="iris.py example")
show(p)
And this is what you should obtain. I additionally put the legend to the right so it is not inserted on top of the plot:
You can use for-loop to plot it:
from bokeh.plotting import figure, show, output_file
from bokeh.sampledata.iris import flowers
colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'}
colors = [colormap[x] for x in flowers['species']]
p = figure(title = "Iris Morphology")
p.xaxis.axis_label = 'Petal Length'
p.yaxis.axis_label = 'Petal Width'
for specie in colormap.keys():
df = flowers[flowers['species']==specie]
p.circle(df["petal_length"], df["petal_width"],
color=colormap[specie], fill_alpha=0.2, size=10, legend=specie)
p.legend.location = "top_left"
output_file("iris.html", title="iris.py example")
show(p)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With