Additional legend in ggplot2

2019-03-03 21:55发布

I have a problem where the legend of my ggplot() does not appear. Here's my code:

plot_bt <- ggplot(NULL, aes(x, v1)) + 
  geom_line(data = nig_bt_1, colour = "black") +
  geom_line(data = nig_bt_2, colour = "blue") +
  geom_line(data = nig_bt_3, colour = "red") + 
  labs(x = "X", y = "Probability")

I tried to make a legend inside this graph but I could not do it. It just does not appear. I try to make a plot of three different types of NIG distribution. In nig_bt_1 etc. I have my values. Those three densities appear but the legend doesn't. I tried the scale_color_manual function too with no success.

Thank you very much.

x <- seq(-7.5,7.5,0.001)
nig_bt_1 <- data.frame(x ,v1 = dnig(x, param = pr_bt_1))
nig_bt_2 <- data.frame(x ,v1 = dnig(x, param = pr_bt_2))
nig_bt_3 <- data.frame(x ,v1 = dnig(x, param = pr_bt_3))

1条回答
虎瘦雄心在
2楼-- · 2019-03-03 22:38

Just do this:

plot_bt <- ggplot(NULL, aes(x, v1)) + 
  geom_line(data = nig_bt_1, aes(colour = "a")) +
  geom_line(data = nig_bt_2, aes(colour = "b")) +
  geom_line(data = nig_bt_3, aes(colour = "c")) + 
  labs(x = "X", y = "Probability") +
  scales_color_manual(values= c("a" = "black", "b" = "blue", "c" = "red"))

A guide can only depict mappings you've defined using aes. The ggplot2 way is of course to first combine the data and use a grouping variable.

查看更多
登录 后发表回答