# Piecewise functions and legend label

If I plot a piecewise function with a legend label like this:

plot(Piecewise([[(0,1),x],[(1,2),x^2]]),legend_label='f(x)')


I get the legend twice. Is there a way to ensure that it appears only one time, i.e. one legend for the whole function?

edit retag close merge delete

Sort by » oldest newest most voted

This is a bug, I think. Here is the documentation for Piecewise plotting.

def plot(self, *args, **kwds):
"""
Returns the plot of self.

Keyword arguments are passed onto the plot command for each piece
of the function. E.g., the plot_points keyword affects each
segment of the plot.


So that includes the legend ones, which however, is not what you want, as opposed to some of the other options. I've added this to the piecewise plotting bug ticket.

Update: Here is a workaround of sorts. Unfortunately, it means plotting each part separately, only labeling one of them.

sage: P = plot(Piecewise([[(0,1),x]]),legend_label='f(x)')
sage: Q = plot(Piecewise([[(1,2),x^2]]),legend_label='')
sage: R = plot(Piecewise([[(0,1),x^2]]),legend_label='g(x)',color='red')
sage: S = plot(Piecewise([[(1,2),x]]),legend_label='',color='red')
sage: P+Q+R+S


Or you could just skip the legend_label option totally on Q and S.

more Here's a slightly different (banana-themed) workaround. Run the following before making the plot:

# monkeypatch legend duplication of trac #11225
def fix_piecewise(fn):
import types
def fixed_plot(self, *args, **kwargs):
from sage.plot.all import plot
return sum([plot(f, a, b, *args, **(dict((k,v) for k,v in kwargs.items() if i == 0 or k != 'legend_label')))
for i, ((a,b),f) in enumerate(self.list())])
def fn2(*args, **kwargs):
ans = fn(*args, **kwargs)
ans.plot = types.MethodType(fixed_plot, ans)
return ans
return fn2

Piecewise = fix_piecewise(Piecewise)


after which it should behave.

more