r语言ggplot绘制图例
时间: 2023-07-18 11:43:03 浏览: 104
要在R语言中使用ggplot绘制图例,可以使用`scale_color_manual()`或`scale_fill_manual()`函数。这两个函数都可以自定义颜色或填充,然后将其应用于ggplot图层中的颜色或填充属性。
例如,要在ggplot中添加自定义颜色的图例,可以使用以下代码:
```
library(ggplot2)
# 创建一个数据框
df <- data.frame(
x = c(1, 2, 3, 4, 5),
y = c(1, 3, 2, 4, 5),
group = c("A", "A", "B", "B", "B")
)
# 创建一个ggplot对象,并设置颜色为group变量
p <- ggplot(df, aes(x, y, color = group)) + geom_point()
# 自定义颜色
my_colors <- c("red", "blue")
# 添加图例
p + scale_color_manual(values = my_colors)
```
同样的,要添加自定义填充的图例,可以使用以下代码:
```
library(ggplot2)
# 创建一个数据框
df <- data.frame(
x = c(1, 2, 3, 4, 5),
y = c(1, 3, 2, 4, 5),
group = c("A", "A", "B", "B", "B")
)
# 创建一个ggplot对象,并设置填充为group变量
p <- ggplot(df, aes(x, y, fill = group)) + geom_bar(stat = "identity")
# 自定义填充
my_colors <- c("red", "blue")
# 添加图例
p + scale_fill_manual(values = my_colors)
```
阅读全文
相关推荐















