我是ggplot2
的新手,而且自几个小时以来一直在努力在情节中添加第二个图例。
我正在使用两个data.frames
(df_1
和df_2
)和两个geom_point
呼叫它们。我设法为df_2
创建了一个图例,但无法为df_1
添加第二个图例。
下面是一个带有情节的代码示例:
########## Create sample data
set.seed(69)
df_1 = data.frame(lat = rnorm(20),
lon = rnorm(20),
cor = c(rep('positive', 12), rep('negative', 8)),
sign = 0)
df_2 = data.frame(lat = rnorm(20),
lon = rnorm(20),
cor = c(rep('positive', 7), rep('negative', 13)),
sign = c(rep(99, 5), rep(95, 6), rep(90,9)))
#### Plot data
library(ggplot2)
p = ggplot() +
# geom_point for df_1
geom_point(data=df_1, aes(x=lon, y=lat),
alpha=0.7, color = 'darkgrey', size = 3) +
# geom_point for df_2
geom_point(data=df_2, aes(x=lon, y=lat, size=sign, colour = cor), alpha = 0.5) +
scale_color_manual(values=c("red", "blue"),
name='cor',
labels = c('neg', 'pos'),
guide = guide_legend(override.aes = list(alpha = 1, size = 3))) +
scale_size(range = c(1,3),
breaks = c(90, 95, 99),
labels = c(0.1, 0.05, 0.01),
name = 'sign',
guide = guide_legend(override.aes = list(colour = 'black',
alpha = 1)))
print(p)
如何为geom_point
的{{1}}调用添加图例?
在带有“未签名”标签的cor(右图例)上添加第三个深灰色点就足够了。
答案 0 :(得分:1)
我想直接的解决方案也是您要求的将第3个Darkgrey点添加到cor图例。为此,您必须:
cor
中的df_1
值更改为相同。df_1
aes
中指定颜色。 scale_color_manual
中第三点的信息。 代码:
# Change values so we would have single color for them
df_1$cor <- "foo"
library(ggplot2)
ggplot() +
geom_point(aes(lon, lat, color = cor), df_1,
alpha = 0.7, size = 3) +
geom_point(aes(lon, lat, size = sign, colour = cor), df_2,
alpha = 0.5) +
scale_color_manual(values = c("darkgrey", "red", "blue"),
labels = c("not sign", "neg", "pos"),
guide = guide_legend(override.aes = list(alpha = 1, size = 3))) +
scale_size(range = c(1, 3),
breaks = c(90, 95, 99),
labels = c(0.1, 0.05, 0.01),
guide = guide_legend(override.aes = list(colour = "black", alpha = 1)))
结果: