ggplot2中的条件图例符号

时间:2016-08-11 00:11:51

标签: r ggplot2 legend

我需要根据数据中的某些条件更改ggplot图例中的符号。例如,在这里,我希望cyl的值大于4的空心圆:

library(ggplot2)
ggplot()+
  geom_point(data = mtcars[mtcars$gear >= 4,],
             aes(mpg,
                 disp,
                 size = gear),
             pch = 21) +
  geom_point(data = mtcars[mtcars$gear < 4,],
             aes(mpg,
                 disp,
                 size = gear)) +
  theme_minimal() +
  guides(size = guide_legend(override.aes = list(pch = c(19, 19, 21, 21, 21))))

enter image description here

我目前的方法是对图例的形状矢量进行硬编码:guides(size = guide_legend(override.aes = list(pch = c(19, 19, 21, 21, 21))))

但是如何通过自动化和概括来避免这种硬编码,这样我就可以更轻松地制作数据具有不同范围的许多情节,我需要更改图例以显示不同的条件?

2 个答案:

答案 0 :(得分:1)

我最终在形状参数上努力工作:

ggplot()+
  geom_point(data = mtcars[mtcars$gear >= 4,],
             aes(mpg,
                 disp,
                 size = gear, shape=factor(1L+(cyl > 4)) ),
             pch = 21) +
  geom_point(data = mtcars[mtcars$gear < 4,],
             aes(mpg,
                 disp,
                 size = gear, shape=factor(1L+(cyl > 4) ))) +
  theme_minimal() +
  guides(size = guide_legend(override.aes = list(pch = c(19, 19, 21, 21, 21))))

我曾尝试shape=1L+(cyl > 4),但一直收到错误&#34;连续变量无法映射到形状&#34;这似乎很荒谬,因为表达方式无法被解释为连续变量&#34;。可能需要一些guide - 操纵图例标题。

答案 1 :(得分:1)

如果您发现将要使用哪些休息时间,则可以在override.aes中设置条件。对于连续比例,我认为默认值为scales::cbreaks(DATA_RANGE, extended_breaks())

library(ggplot2)
library(scales)

cutoff <- 4 # set the condition value here so we don't hard-code it in the plot code

ggplot(mtcars, aes(x = mpg, 
                   y = disp, 
                   size = gear, 
                   shape = gear >= cutoff)) +
  geom_point() +
  theme_minimal() +
  scale_shape_manual(values = c(19, 21),
                     name = "gear",
                     guide  = "none") +
  guides(size = guide_legend(override.aes = list(pch = ifelse(
    cbreaks(range(mtcars$gear), 
            extended_breaks())$breaks >= cutoff, 21, 19
  ))))