将Boxplot与其他图表类型结合使用时,在带有ggplot的图例中包含boxplot图标

我在描述图中同时包含了geom_boxplot(用于连续测量)和geom_point(用于二进制测量)。使用以下汽车数据集的示例代码。

我想添加一个图例,其中列出了点(形状9)反映了二进制变量,而箱线图反映了连续变量。换句话说,我想知道我是否可以用两个元素制作图例:

[shape 9图标]二进制变量

[boxplot图标]连续变量

library(reshape2)
library(dplyr)
library(ggplot2)

df <- cars %>%
  mutate(dist = ifelse(dist > 10, 1, 0)) %>%
  reshape2::melt()

ggplot(data=df, aes(x = value, y = factor(variable))) +
  geom_boxplot(aes(x = ifelse(variable == "speed", value, NA), y = variable),
               width=0.2, outlier.shape = NA) +
  geom_point(data=df %>% filter(variable == "dist"), aes(x = mean(value), y = variable),
             shape=9)
评论
  • 浮云、暖
    浮云、暖 回复

    要获得图例,您需要确保您的几何图形具有关联的比例尺。在这种情况下,您可能需要一个形状比例和一个填充比例:

    ggplot(data = df, aes(x = value, y = factor(variable), fill = factor(variable))) +
      geom_boxplot(aes(x = ifelse(variable == "speed", value, NA), y = variable),
                   width = 0.2, outlier.shape = NA) +
      geom_point(data = df %>% filter(variable == "dist"), 
                 aes(x = mean(value), y = variable, shape = factor(mean(value)))) +
      scale_shape_manual(values = 9, name = "dist") +
      scale_fill_manual(breaks = c("speed", "speed"), values = c("white", "white"), 
                        na.translate = FALSE, name = "speed")
    

    enter image description here