Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Legend in a graph when using package Gadfly.jl in Julia

I am using Julia for Financial Data Processing and then plotting graphs based on the financial data.

on X-Axis of graph I am plotting dates (per day prices) on Y-Axis I am plotting Stock Prices, MovingAverage13 and MovingAverage21

I am currently using DataFrames to plot the data

Code-

df=DataFrame(x=dates,y1=pricesClose,y2=m13,y3=m21)
l1=layer(x="x",y="y1",Geom.line,Theme(default_color=color("blue")));
l2=layer(x="x",y="y2",Geom.line,Theme(default_color=color("red")));
l3=layer(x="x",y="y3",Geom.line,Theme(default_color=color("green")));
p=plot(df,l1,l2,l3);
draw(PNG("stock.png",6inch,3inch),p)

I am Getting the graphs correctly but I am not able to add a Legend in the Graph that shows blue line is for Close Prices red line is for moving average 13 green line is for moving average 21

How can we add a legend to the graph?

like image 290
Jay Dharmendra Solanki Avatar asked Feb 12 '14 07:02

Jay Dharmendra Solanki


2 Answers

I understand from the comments in this link that currently it is not possible to get a legend for a list of layers.

Gadfly is based on Hadley Wickhams's ggplot2 for R and thus the usual pattern is to arrange data into a DataFrame with a discrete column for labelling purposes. In your case, this approach would look like:

x = 1:10
df1 = DataFrame(x=x, y=2x, label="double")
df2 = DataFrame(x=x, y=x.^2, label="square")
df3 = DataFrame(x=x, y=1./x, label="inverse")

df = vcat(df1, df2, df3)

p = plot(df, x="x", y="y", color="label", Geom.line,
         Scale.discrete_color_manual("blue","red", "green"))

draw(PNG("stock.png", 6inch, 3inch), p)

stock.png

like image 140
Nico Avatar answered Nov 09 '22 17:11

Nico


Now you can try with manual_color_key. The only change in your code is needed here:

p=plot(df,l1,l2,l3, Guide.ylabel("Some text"), Guide.title("My title"), Guide.manual_color_key("Legend", ["I'm blue l1", "I'm red l2", "I'm green l3"], ["blue", "red", "green"]))

like image 24
Maciek Leks Avatar answered Nov 09 '22 16:11

Maciek Leks