0

I'm trying to get a legend to show up in a left chart I've developed. It's not showing up. I've checked ggplot legend not working with scale_colour_manual as well as How to add a legend in ggplot (not showing up) to no avail.

Here is some sample data:

#x axis values
deciles <- c(1:10)
#model_1
decile_act_pp <- c(393.6773, 243.0795, 250.2033, 220.0076, 180.7292,
               187.3803,208.8504,162.9708,140.9405,107.7656)
#model_2
model2_pp_norm <- c(537.9617, 306.0807, 244.6228, 207.8051, 181.8801,
161.3744,142.8224,125.3262,107.5905,  80.13438)
#model_3
model1_pp_norm <- c(515.9927,297.8425, 240.8723, 206.6129, 183.6805, 
164.3337, 148.4509,134.1227, 115.0055, 88.68549)
#combine to make a chart
df <- as.data.frame(cbind(deciles, decile_act_pp, model2_pp_norm, 
model1_pp_norm))

#develop the chart

ggplot(data = df, aes(x = as.factor(deciles), group = 1)) +
geom_point(aes(y = decile_act_pp), color = "blue") +
geom_line(aes(y = decile_act_pp), color = "blue") +
geom_point(aes(y = model2_pp_norm), color = "red") +
geom_line(aes(y = model2_pp_norm), color = "red") +
geom_point(aes(y = model1_pp_norm), color = "green") +
geom_line(aes(y = model1_pp_norm), color = "green") +
xlab("Deciles") +
labs(colour="Datasets",x="Deciles",y="Pure Premium") +
scale_color_manual('', limits = c('decile_act_pp', 'model2_pp_norm', 
'model1_pp_norm'), values = c("blue", "red", "green"))

The chart look exactly as I want it minus missing the legend. Can anyone tell me what I'm doing wrong?

Jordan
  • 1,415
  • 3
  • 18
  • 44
  • 1
    Yes, figure looks exactly like you want, but it's not plotted in the right way and that's why you don't get the legend. Check [this possible duplicate](https://stackoverflow.com/questions/3427457/ggplot-and-r-two-variables-over-time) – pogibas Feb 08 '18 at 19:40
  • Why would you expect a legend to be printed if you map nothing to color, shape or size? – PejoPhylo Feb 08 '18 at 19:41
  • 1
    In ggplot, you get a legend by mapping a data column to, say, `color` *inside* `aes`. In your plot, you've hard-coded the color for each line outside of `aes`. Your data frame is currently in "wide" format. Instead, stack your model data frames into a single data frame with a new column marking the model each row of data refers to, and map color to that new column. – eipi10 Feb 08 '18 at 19:47

1 Answers1

0
library(reshape2) 
df2 <- melt(data = df, id.vars = 1)
ggplot(data = df2, aes(x = as.factor(deciles), group = 1)) + geom_point(aes( y=value, color = variable)) + geom_line(aes(y = value, group = variable, color = variable))
PejoPhylo
  • 469
  • 2
  • 11