自定义图例形状和大小ggplot2

时间:2019-05-23 15:52:40

标签: r ggplot2 legend

我试图自定义图例,我想用所需的指定颜色填充图例,并删除其中的任何斜杠或符号。

theme(axis.title.x = element_blank(),
      axis.title.y = element_blank(),
      axis.title.y.right = element_blank(),
      axis.ticks.x=element_blank(),
      axis.ticks.y=element_blank(),
      axis.text.x=element_text(angle = 45, size = 10, vjust = 0.5, face = "bold"),
      axis.text.y=element_blank(),
      axis.line = element_line(colour = "white"),
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.border = element_blank(),
      panel.background = element_blank(),
      plot.background=element_blank(),
      legend.position="left",
      legend.title=element_blank(),
      legend.text = element_text(size = 16, face = "bold"),
      legend.key = element_rect(fill = c("red", "blue")))

enter image description here

但是,我仍然需要添加一些东西来满足自己的愿望。
legend.key在这里似乎不正确。
我想要的是:哦!但第一个是红色而不是橙色。

enter image description here

1 个答案:

答案 0 :(得分:2)

我发现最好的解决方案是使用指南功能。实际上,以下代码可以完成工作:

df <- data.frame(value = rnorm(100), group = as.factor(sample(c(1, 2), size = 100, replace = T)))

ggplot(df, aes(x = value, y=value, col = group)) +
  scale_color_manual(values = c("1" = "red", "2" = "blue")) +
  geom_point() + 
  guides(colour = guide_legend(override.aes = list(shape = 15, size = 10))) +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        axis.title.y.right = element_blank(),
        axis.ticks.x=element_blank(),
        axis.ticks.y=element_blank(),
        axis.text.x=element_text(angle = 45, size = 10, vjust = 0.5, face = "bold"),
        axis.text.y=element_blank(),
        axis.line = element_line(colour = "white"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank(),
        plot.background=element_blank(),
        legend.position="left",
        legend.title = element_blank(),
        legend.text = element_text(size = 16, face = "bold"),
        legend.key = element_blank(),
        legend.box.background =  element_blank())

我的意思是关于stackoverflow的其他几篇文章:

ggplot2 custom legend shapes

How to increase the size of points in legend of ggplot2?