R语言 如何在ggplot2中使图例键填充透明
在这篇文章中,我们将看到如何在R编程语言中的ggplot2中使图例键填充透明。
注意: 这里我们将使用一个线图,同样的方法也可以应用于任何其他的图。
让我们先画一个普通的图,这样就能看出区别。
例子
# Load Package
library("ggplot2")
# Create DataFrame
DF <- data.frame(X = rnorm(50),
Y = rnorm(50),
Users = c("User1", "User2", "User3",
"User4", "User5"))
# Generate LineGraph from DataFrame
# using ggplot2
ggplot(DF,aes(X, Y, color = Users))+
geom_line(size = 1)
输出
带有默认图例键的线图
在上面的图中,你可以清楚地看到,图例键的背景是灰色的。因此,现在我们要通过使用theme()函数将其转换为透明的。theme()本身是一个非常大的函数,包含了很多主题元素,我们可以将其应用到绘图中,使我们的绘图看起来更美观。为了改变Legend键的背景,我们使用 legend.key, 它指定了Legend键下面的背景。
语法: theme(legend.key)
参数 :
- legend.key: 用于指定图例键下方的背景。我们将 element_rect 函数作为它的值。
返回: 图的主题
此外,我们指定 element_rect() 函数作为 legend.key 的值,它通常用于背景和边框。它也有一些自定义的参数,如填充、颜色、大小和线型,但在这里,为了使Legend Keys具有透明背景,我们将只使用其中的 填充 参数。
语法 : element_rect(fill)
参数:
- fill : 用颜色填充。
返回: 对背景和边框的修改。
语法
theme(legend.key = element_rect(fill))
例子
# Load ggplot2 Package
library("ggplot2")
# Create DataFrame for Plotting
DF <- data.frame(X = rnorm(50),
Y = rnorm(50),
Users = c("User1", "User2", "User3",
"User4", "User5"))
# Generate LineGraph with transparent fill
# of Legend Keys.
ggplot(DF,aes(X, Y, color = Users))+
geom_line(size = 1)+
theme(legend.key = element_rect(fill = "transparent"))
输出
带有透明填充图例键的线图