12

I made a simple classic plot with ggplot2 which is two graphs in one. However, I'm struggling in showing the legend. It's not showing the legend. I didn't use the melt and reshape way, I just use the classic way. Below is my code.

df <- read.csv("testDataFrame.csv")

graph <- ggplot(df, aes(A)) + 
  geom_line(aes(y=res1), colour="1") +
  geom_point(aes(y=res1), size=5, shape=12) +
  geom_line(aes(y=res2), colour="2") +
  geom_point(aes(y=res2), size=5, shape=20) +
  scale_colour_manual(values=c("red", "green")) +
  scale_x_discrete(name="X axis") +
  scale_y_continuous(name="Y-axis") +
  ggtitle("Test") 
  #scale_shape_discrete(name  ="results",labels=c("Res1", "Res2"),solid=TRUE) 

print(graph)

the data frame is:

 A,res1,res2
 1,11,25
 2,29,40
 3,40,42
 4,50,51
 5,66,61
 6,75,69
 7,85,75

Any suggestion on how to show the legend for the above graph?

jay.sf
  • 60,139
  • 8
  • 53
  • 110
SimpleNEasy
  • 879
  • 3
  • 11
  • 32

1 Answers1

12

In ggplot2, legends are shown for every aesthetic (aes) you set; such as group, colour, shape. And to do that, you'll have to get your data in the form:

A variable value
1     res1    11
...    ...    ...
6     res1    85
7     res2    75

You can accomplish this with reshape2 using melt (as shown below):

require(reshape2)
require(ggplot2)

ggplot(dat = melt(df, id.var="A"), aes(x=A, y=value)) + 
      geom_line(aes(colour=variable, group=variable)) + 
      geom_point(aes(colour=variable, shape=variable, group=variable), size=4)

For example, if you don't want colour for points, then just remove colour=variable from geom_point(aes(.)). For more legend options, follow this link.

enter image description here

Arun
  • 116,683
  • 26
  • 284
  • 387
  • thank you. How do I change the name of the colour variable. Instead of showing variable for the legend, can I rename such as Results. Is there is a way?. With shape I just removed the colour and have used scale_shape_discrete(name ="Results",labels=c("Res1", "Res1"),solid = TRUE) and it works. Not sure how to change it with colour? – SimpleNEasy Mar 14 '13 at 20:05
  • Direct/straightforward way is to save the melted data.frame to a variable like: `df.m <- melt(df, id.var="A")`. Now, change `df.m` column names to whatever you want. – Arun Mar 14 '13 at 20:21