How to show legend in hvPlot when only one variable of y

#Question: how to keep legend even there is only one variable to plot?

case #1: if y=“actual” or “forecast”, the legend didn’t show up

#case # 2 legend only show up when number of y variables is >=2, like , y=[“actual”,“forecast”]

import hvplot.pandas
import pandas as pd

df = pd.DataFrame(
{
“actual”: [100, 150, 125, 140, 145, 135, 123],
“forecast”: [90, 160, 125, 150, 141, 141, 120],
“numerical”: [1.1, 1.9, 3.2, 3.8, 4.3, 5.0, 5.5],
“date”: pd.date_range(“2022-01-03”, “2022-01-09”),
“string”: [“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”],
},
)
scatter = df.hvplot.scatter(
x=“numerical”,
#y=[“actual”,“forecast”],
y=“actual”,
ylabel=“value”,
legend=“right”,
height=500,
color=["#f16a6f", “#1e85f7”],
size=100,
)
scatter

There is an open issue for this here: Add legend to plot with only 1 curve · Issue #4196 · holoviz/holoviews · GitHub. you can try the work-around (adding the label keyword to the scatter, and then creating an overlay):

import holoviews as hv
import hvplot.pandas
import pandas as pd

df = pd.DataFrame({
    'actual': [100, 150, 125, 140, 145, 135, 123],
    'forecast': [90, 160, 125, 150, 141, 141, 120],
    'numerical': [1.1, 1.9, 3.2, 3.8, 4.3, 5.0, 5.5],
    'date': pd.date_range('2022-01-03', '2022-01-09'),
    'string': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
})

scatter = df.hvplot.scatter(
    x='numerical',
    #y=[“actual”,“forecast”],
    y='actual',
    ylabel='value',
    label='legend-text',  # add this!
    show_legend=True,
    legend='right',
    height=500,
    color=['#f16a6f', '#1e85f7'],
    size=100,
)

hv.Overlay([scatter, scatter])

It is definitely not ideal, but it works.

2 Likes

Thank you !

1 Like