You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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 = 1 controls 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:58:14