如何在 R 中使用 ggplot2 更改图例形状?
在本文中,我们将讨论如何在 R 编程语言中使用 ggplot2 仅更改图例形状。这里使用 ScatterPlot,同样可以应用于任何其他绘图。
Syntax : sample(x, size, replace = TRUE)
Parameters :
- x : either a vector of one or more values from which we want to choose the values or a positive integer. here we use column of Usernames as a first parameter (x).
- size : represents the length i.e number of values to choose from x.
- replace = TRUE : To assure that no value chosen twice i.e choose all different values from x.
Return : returns sample data as per arguments.
让我们首先创建一个常规图,以便差异明显。
例子:
R
# Load Package
library("ggplot2")
# Create DataFrame for plotting
data<-data.frame(x = rnorm(20),
y = rnorm(20),
Users = sample(c("User 1", "User 2",
"User 3", "User 4",
"User 5"),
20, replace=TRUE))
# Create ScatterPlot using ggplot2
ggplot(data,aes(x, y, color = Users))+
geom_point(size = 10)
R
# Load Package
library("ggplot2")
# Create DataFrame for plotting
data<-data.frame(x = rnorm(20),
y = rnorm(20),
Users = sample(c("User 1", "User 2", "User 3",
"User 4", "User 5"),
20, replace=TRUE))
# Create a ScatterPlot with changed
# shape of Legend using guides()
# function
ggplot(data,aes(x, y, color = Users))+
geom_point(size = 10)+
guides(color = guide_legend(
override.aes=list(shape = 18)))
输出:
现在,如果我们只想更改图例形状,那么我们必须向 geom_point() 函数添加 guides() 和 guide_legend()函数。在 guides()函数,我们采用名为 'color' 的参数,因为我们在 ggplot()函数使用了颜色参数作为图例。 'color' 调用 guide_legend() 引导函数作为值。在 guide_legend()函数,我们接受一个名为 override.aes 的参数,该参数将图例的美学参数列表作为值。
Syntax : guides(…)
Parameter :
- … : either a string or call to a guide function. here we call guide_legend() guide function.
Return : each scale can be set scale-by-scale
Syntax : guide_legend(override.aes = list() )
Parameter :
- override.aes : List of aesthetic parameters of Legend. here we want to change only the shape of the legend key, So we assign ‘shape’ parameter to list. it can have some other parameters as per user’s requirement like color, size, etc as well.
Return : Legend Guides for various scales
这里是形状参数的设定值。下面给出了可供选择的值:
例子:
电阻
# Load Package
library("ggplot2")
# Create DataFrame for plotting
data<-data.frame(x = rnorm(20),
y = rnorm(20),
Users = sample(c("User 1", "User 2", "User 3",
"User 4", "User 5"),
20, replace=TRUE))
# Create a ScatterPlot with changed
# shape of Legend using guides()
# function
ggplot(data,aes(x, y, color = Users))+
geom_point(size = 10)+
guides(color = guide_legend(
override.aes=list(shape = 18)))
输出: