Legend for layers with specified colors in Gadfly

1,144 views
Skip to first unread message

Tomas Lycken

unread,
Sep 28, 2014, 5:52:07 PM9/28/14
to julia...@googlegroups.com

The only way I’ve figured out to have two layers with different-color lines and a legend is to do something like this:

plot(
    layer(
        x = x1,
        y = y1,
        color = ["Line 1" for i in 1:length(x1)],
        Geom.path,
    ),
    layer(
        x = x2,
        y = y2,
        color = ["Line 2" for i in 1:length(x2)],
        Geom.path
    ),

    Guide.colorkey("Legend title"),
)

This works in that it gives me a legend with the text I want, but it doesn’t give me any way to control the color of the lines - I usually do it with a Theme(default_color=color("red")) or similar, but since I’ve given each datapoint a color value (which isn’t really a color) that doesn’t have any effect.

Is there any way I can get a layered plot, where each layer has its own legend entry, and at the same time control the color of the plot elements in each layer?

// T

Leah Hanson

unread,
Sep 28, 2014, 11:37:57 PM9/28/14
to julia...@googlegroups.com
It don't know if you'll like it better, but here's another way to get the same effect using Gadfly. The `Scale.discrete_color_manual` controls the colors used by the scale.

~~~
using Gadfly, DataFrames

# populate the data in the format from your example
x1 = [1:10]; y1=[12:21]
x2 = [1:10]; y2 = [30:-1:21]

# make a 3 column DataFrame (x,y,line); maybe not the best way to make a DataFrame, but it works.
df = DataFrame(Dict((:x,:y,:line),([x1,x2],[y1,y2],[["Line 1" for i=1:10],["Line 2" for i=1:10]])))

# plot the DataFrame
plot(df,x=:x,y=:y,color=:line,Scale.discrete_color_manual("red","purple"),Geom.line,Guide.colorkey("Legend title"))
~~~

-- Leah

Daniel Jones

unread,
Sep 29, 2014, 12:08:28 PM9/29/14
to julia...@googlegroups.com

There is a sort of brute-force way of doing this which is potentially nicer: Guide.manual_color_key

Reply all
Reply to author
Forward
0 new messages