繁体   English   中英

图例未更改 ggplot2 中的 colors

[英]Legend not changing colors in ggplot2

我正在尝试 plot 分散 plot 与 22 个变量,所以他们都需要有不同的标记。 我想从 RColorBrew 重复一些形状和 colors,一切正常,除了我选择的 colors 没有更新的图例(请参见下图)。 我还在下面附上了一个工作示例。 我可能做错了什么?

#!/usr/bin/env Rscript

library(ggplot2)
library(ggpubr)
library(RColorBrewer)

theme_set(
    theme_pubr()
  )

data <- data.frame(
    x = c(1:22),
    y = as.factor(c(1:22))
)

shapes <- rep(15:18, 6)

colors <- rep(brewer.pal(n = 11, name = "Paired"), 2)

plot <- ggplot(data, aes(x=x, y=y, group=y, size=9, color=colors)) +
  geom_point(aes(shape=y)) +
  scale_shape_manual(values=shapes) +
  scale_size(guide="none") +
  guides(fill="none", color="none")

plot <- plot + theme(panel.grid.major=element_line(colour="gray", size=0.2),
  panel.grid.minor=element_line(colour="gray", size=0.2))

print(plot)

黑色传奇

有两个问题:

  1. 我想让你的 colors 在color aes 上使用scale_color_manual和 map y ,就像你对 shape 所做的那样

  2. 您的图例没有着色的原因是您设置了guides(color = "none")

library(ggplot2)
library(ggpubr)
library(RColorBrewer)

theme_set(
  theme_pubr()
)

data <- data.frame(
  x = c(1:22),
  y = as.factor(c(1:22))
)

shapes <- rep(15:18, 6)

colors <- rep(brewer.pal(n = 11, name = "Paired"), 2)

plot <- ggplot(data, aes(x = x, y = y, group = y, size = 9)) +
  geom_point(aes(shape = y, color = y)) +
  scale_shape_manual(values = shapes) +
  scale_color_manual(values = colors) +
  scale_size(guide = "none") +
  guides(fill = "none")

plot + theme(
  panel.grid.major = element_line(colour = "gray", size = 0.2),
  panel.grid.minor = element_line(colour = "gray", size = 0.2)
)

我发现了很多事情。 我在这里一一分解:

  • 您在aes中包含colors但它不是数据的一部分,它只是调色板,因此不应包含在此处。 aes告诉 ggplot 要显示什么数据,而不是如何格式化它。
  • geom_point需要 color 和 shape aes参数,以便它可以将它们组合起来,然后告诉图例它是如何做到的。
  • 为了控制使用的调色板,我添加了scale_color_manual ,类似于您已经使用scale_shape_manual手动调整格式
  • 删除最后的guides线。 通过设置color = "none"它阻止颜色被添加到图例中。

试试下面的代码段。

data <- data.frame(
  x = c(1:22),
  y = as.factor(c(1:22))
)

shapes <- rep(15:18, 6)

colors <- rep(brewer.pal(n = 11, name = "Paired"), 2)

#OLD: plot <- ggplot(data, aes(x=x, y=y, group=y, size=9, color=colors)) +
plot <- ggplot(data, aes(x=x, y=y, group=y, size=9)) +  
  
  #OLD: geom_point(aes(shape=y)) +
  geom_point(aes(shape=y, color=y)) +
  
  scale_shape_manual(values=shapes) +
  
  #NEW LINE
  scale_color_manual(values = colors) + 

    scale_size(guide="none") 
# REMOVED guides(fill="none", color="none")


plot <- plot + theme(panel.grid.major=element_line(colour="gray", size=0.2),
                     panel.grid.minor=element_line(colour="gray", size=0.2))

print(plot)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM