如何在ggplot2中定义单个图例元素?

丹尼·比奇瑙(Danny Beachnau)

我需要为该图表创建明智的图例。

我正在使用R版本3.5.2和ggplot2版本3.1.0.9000。

到目前为止,我有:

as.data.frame(list(
  name = c('alice', 'bob', 'charlie'),
  y = c(2, 3, 3.5),
  y_min = c(1, 1.5, 1.25),
  y_max = c(4, 3.5, 7),
  asterisk = c(6, 3.75, 9)
  )
) %>%
  ggplot(aes(y = y, x = name)) +
  geom_point(aes(color = 'main', shape = 'main'), size = 4) +
  geom_point(aes(y = asterisk, color = 'asterisk', shape = 'asterisk'), size = 6) +
  scale_color_manual(values = list('main' = 'black', 'asterisk' = 'red')) +
  scale_shape_manual(values = list('main' = 16, 'asterisk' = 42)) +
  geom_segment(aes(y = y_min, yend = y_max, xend = name)) +
  coord_flip()

在此处输入图片说明

我希望使图例仅显示一个大黑点和一个小红色星号,最好在一个标题下。没有大的红点或小黑星号,并且这些符号出现在图例中令人困惑。

马库斯

您需要给两个图例使用相同的名称,以便它们成为一个

ggplot(dat, aes(y=y, x=name)) +
  geom_point(aes(color='main', 
                 shape='main'), size=4) +
  geom_point(aes(y=asterisk, 
                 color='asterisk', 
                 shape='asterisk'), size=6) +
  scale_color_manual(name = "legend_title", # changed name here
                     values=c('main'='black', 'asterisk'='red')) +
  scale_shape_manual(name = "legend_title", # and here
                     values=c('main'=16, 'asterisk'=42)) +
  geom_segment(aes(y=y_min, yend=y_max, xend=name)) +
  coord_flip()

在此处输入图片说明

数据

dat <- data.frame(
  name = c('alice', 'bob', 'charlie'),
  y = c(2, 3, 3.5),
  y_min = c(1, 1.5, 1.25),
  y_max = c(4, 3.5, 7),
  asterisk = c(6, 3.75, 9), stringsAsFactors = FALSE) 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章