14

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?

kaslusimoes
  • 235
  • 2
  • 13
  • This was not possible at the time this question was posted, but this functionality is now available via `Guide.manual_color_key`. See [here](https://github.com/dcjones/Gadfly.jl/issues/344) for more detail. – Colin T Bowers Jun 18 '15 at 04:22

2 Answers2

15

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

Nico
  • 1,070
  • 1
  • 10
  • 14
  • Nico, Thanks alot, I was stuck for so much time here. Now I can procede with my project. – Jay Dharmendra Solanki Feb 17 '14 at 06:02
  • What if I'm plotting functions like this: plot([sin, cos], 0, 5)? The functions are labeled "f1" and "f2" on the plot and I'd like to change that. – user697683 Dec 06 '14 at 15:44
  • @user697683 This deserves to open a new question. – Nico Dec 06 '14 at 20:46
  • I think `Guide.manual_color_key` allows you to do pretty much whatever you want with the legend, and it can be used when a list of layers is input to `plot`. [See here](https://github.com/dcjones/Gadfly.jl/issues/344). EDIT: just saw the date on your answer. This feature was not available in Feb 2014 :-) – Colin T Bowers Jun 18 '15 at 04:19
5

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"]))

Maciek Leks
  • 1,288
  • 11
  • 21