简体   繁体   中英

R ggplot: line around legend

I am trying to use ggplot2 for my data plotting.

For purely superficial reasons I would like to have a line around my legend so as to better distinguish it from the plot (ie a black outline around the legend box). I could not find an answer to this question on any forum, but maybe you have a tip?

library(ggplot2)

Res = matrix(ncol = 3, nrow = 500)
Res[,1] = 1:500
Res[,2] = sin((2*pi)/100*Res[,1])
Res[,3] = cos((2*pi)/100*Res[,1])
Res = as.data.frame(Res)
colnames(Res) = c("X", "Y1", "Y2")

ggplot(Res, aes(X)) + 
  geom_line(aes(y = Y1, colour = "1"), size = 2) +
  geom_line(aes(y = Y2, colour = "2"), size = 2) +
  scale_color_discrete(name = "Y's", labels = c(" sine", " cosine")) +
  theme(legend.position=c(0.9, 0.7))

This will give an outline around legend

library(ggplot2)

Res = matrix(ncol = 3, nrow = 500)
Res[,1] = 1:500
Res[,2] = sin((2*pi)/100*Res[,1])
Res[,3] = cos((2*pi)/100*Res[,1])
Res = as.data.frame(Res)
colnames(Res) = c("X", "Y1", "Y2")

ggplot(Res, aes(X)) + 
  geom_line(aes(y = Y1, colour = "1"), size = 2) +
  geom_line(aes(y = Y2, colour = "2"), size = 2) +
  scale_color_discrete(name = "Y's", labels = c(" sine", " cosine")) +
  theme(legend.position=c(0.9, 0.7)) +  
  theme(legend.background = element_rect(colour = 'black', fill = 'white', linetype='solid'))

You can read more about legend settings here https://github.com/tidyverse/ggplot2/wiki/Legend-Attributes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM