如何为R语言ggplot2绘图中的图例添加黑色边框?
Add Black Border to ggplot2 Legend
Great question! Adding a distinct black border to your ggplot2 legend is a simple tweak in the theme() function that makes your plot much cleaner. Here's how to modify your code to achieve this:
Modified Full Code
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), # Add black border around the entire legend box legend.background = element_rect(color = "black", fill = "white", size = 1), # Optional: Remove gray background from individual legend items for consistency legend.key = element_rect(fill = "white") )
Key Explanations
legend.background = element_rect(...): This is the core of the solution:color = "black"sets the outer border of the legend to black.fill = "white"changes the legend's background to white (so it stands out against your plot area—you can skip this if you prefer a transparent background).size = 1controls the thickness of the border; adjust this number to make the border thicker or thinner as needed.
legend.key = element_rect(fill = "white"): This optional line removes the default gray background from each individual legend entry, creating a more cohesive look with the white legend background.
内容的提问来源于stack exchange,提问作者Arne
相关产品推荐
相关产品推荐

