Ask Your Question

Piecewise functions and legend label

asked 2011-11-19 10:37:47 -0500

sagefan gravatar image

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


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 flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted

answered 2011-11-19 13:58:45 -0500

kcrisman gravatar image

updated 2011-11-21 13:20:24 -0500

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.

edit flag offensive delete link more


Is there any workaround?

sagefan gravatar imagesagefan ( 2011-11-19 20:24:03 -0500 )edit

answered 2011-11-21 14:18:48 -0500

DSM gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2011-11-19 10:37:47 -0500

Seen: 386 times

Last updated: Nov 21 '11