图例未出现在 ggplot geom_point 色彩美学中

legend not appearing for ggplot geom_point color aesthetics

我正在尝试为 ggplot geom_point 颜色美学生成图例。我尝试了各种组合并浏览了已经提出的问题,但还没有想出解决方案。

library (tidyverse)
library (ggplot2)

df <- structure(list(name = c("name1.1", "name1.2", "name1.3", 
                        "name2.1", "name2.2", "name2.3", "name3.1", "name3.2", "name3.3"), 
                     shape = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("shape1", "shape2", "shape3"), class = "factor"), 
group_num = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("group_1", "group_2", "group_3"), class = "factor"), 
x_value = c(0.9, 1, 1.1, 0.9, 1, 1.1, 0.9, 1, 1.1), 
var1 = c(8762, 40679, 49441, 4544, 21064, 25608, 4218, 19615, 23833), 
var2 = c(3.31, 3.02, 3.07, 3.23, 2.88, 2.94, 3.39, 3.17, 3.21), 
var3 = c(28994.1, 122769.8, 151763.9, 14689.2, 60675.8, 75365, 14304.9, 62094, 76398.9), 
var4 = c(230344, 944725, 1175069, 230344, 944725, 1175069, NA, NA, NA), 
var5 = c(26.29, 23.22, 23.77, 50.69, 44.85, 45.89, NA, NA, NA)), row.names = c(NA, -9L), class = c("tbl_df", "tbl", "data.frame"))


df.plot <- ggplot(df, aes(x = x_value, 
                          y = var2)) +
  geom_point(aes(
    size = var4,
    shape = shape,
    #color = shape)) +
    color = var5),
    alpha = 0.8) +
  scale_shape_manual(values = c("shape1" = 19, "shape2" = 15, "shape3" = 17), name = "Shapes", guide = guide_legend(override.aes = list(size = 3, fill = "black"))) +
  scale_size (range = c(2, 10), breaks = c(250000, 500000, 1000000), labels = c("250,000", "500,000", "1,000,000")) +
  #scale_fill_continuous(palette = viridis) +
  #scale_fill_gradient(low="orange2", high="darkblue", na.value ="gray30") +
  scale_color_viridis (breaks = c(10, 15, 21), labels = c("10", "15", "21"), name = "Var5") +
  coord_cartesian(xlim=c(0.7, 1.3), ylim=c(2.8, 3.4)) +
  scale_y_continuous(breaks = c(seq (from = 2.8, to = 3.4, by = 0.2))) +
  scale_x_continuous(breaks = c(seq (from = 0.7, to = 1.3, by = 0.1))) +
  geom_point(data = subset(df, is.na(var4)), aes(shape = shape, color = var5),  ####create similar shapes with gray color when var4 and/or var5 are NA
            size = 1.5, fill = "gray30") +
  theme_bw() +
  #guides(color = guide_legend(override.aes = list(size = 3), list(fill = scale_color_viridis ()))) +
  theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(), 
        axis.title.x = element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x = element_blank()) +
  facet_wrap(~ group_num)

我得到的输出:

如果我在没有 scale_color_viridis (breaks = c(10, 15, 21), labels = c("10", "15", "21"), name = "Var5") 的情况下尝试,我会得到以下情节。

我想要生成的是 viridis 调色板中的颜色图例。

我曾尝试在 aes 之外使用 guide_legend(override.aes)guides 参数,但没有成功

如有任何帮助,我们将不胜感激

问题是您指定的 none 个中断点落在数据范围内。因此没有什么可以着色的,所以没有比例可以显示。

range(df$var5, na.rm = T)
#> [1] 23.22 50.69

如果换句话说:

scale_colour_viridis_c(breaks = c(10, 15, 21, 30, 40, 50), limits = c(10, 50))

你会得到