首页 > 解决方案 > 使用 face_wrap,如何在 ggplot2 中创建具有颜色和形状的图例

问题描述

我正在使用 face_wrap 在四个不同的组中展示我的结果(对应于变量“Tipo”的图表)。每个组都有自己的形状,在每个组中,我使用不同的颜色来表示不同类型的结果(在本例中,是不同类型的疾病“Enfermedad”)。因此,我不能将“形状”和“颜色”分配给同一个变量,并且合并两列也不适用于我的情况。所以基本上,我已经设法为每个组分配了四种不同的形状和 16 种不同的颜色,但我没有设法创建一个具有颜色和形状的图例。先感谢您!

我使用的表如下所示:

 Enfermedad               Casos     Año        Tipo
 Amebiasis intestinal      100      1998       Parasitaria
 Amebiasis intestinal      250      1999       Parasitaria
 Fiebre tifoidea           300      1998       Bacteriana
 Fiebre tifoidea           225      1999       Bacteriana
 Hepatitis vírica A         50      1998       Vírica
 Hepatitis vírica A         33      1999       Vírica

这是我的代码:

library(RColorBrewer)

EnfermGastro<- read_excel("...")

colourCount = length(unique(EnfermGastro$Enfermedad))
getPalette = colorRampPalette(brewer.pal(16, "Set1"))

ggplot(EnfermGastro, aes(x=Año,y=Casos,shape=Tipo, colour=Enfermedad)) +

geom_point(size=2.5) +

scale_shape_manual(values =c(16, 1, 18, 8)) +

scale_fill_manual(values= getPalette(colourCount)) +

scale_x_continuous( breaks=c(1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,
                           2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018)) +
scale_y_continuous(labels=comma) +

theme_bw() +
theme(axis.line=element_line(colour = "black"),
      panel.grid.major.y = element_line(colour="grey75", linetype="dotted"),
      panel.grid.major.x = element_line(colour="grey75", linetype="dotted"),
      panel.border=element_blank(),
      legend.background=element_rect(fill="grey80", colour="black"),
      legend.title = element_text(size= 10),
      legend.text = element_text(size= 8),
      legend.position="bottom") +

   facet_wrap(~Tipo, scale= "free")

在此处输入图像描述

标签: rggplot2legend

解决方案


好的,这是一个可能的解决方案,不是最好的解决方案,因为我只想有 4 种不同的形状,每个方面都有一种形状,但至少我设法在 ggplot2 中创建了一个具有颜色和形状的图例。所以,我所做的是在 16 种不同的疾病中重复相同的 4 种形状。因此,我将“形状”和“颜色”分配给变量Enfermedad(疾病)并使用 scale_shape_manual。同样,这并不是我真正想要的,所以如果有人有更好的解决方案,我会非常欢迎!

ggplot(EnfermGastro, aes(x=Año,y=Casos, shape=Enfermedad, colour=Enfermedad)) +

geom_point(size=2.5) +

scale_shape_manual(values =rep.int(c(16, 1, 18, 8),times=4)) +

scale_fill_manual(values= getPalette(colourCount)) +

scale_x_continuous( breaks=c(1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,
                        2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018)) +
scale_y_continuous(labels=comma) +

theme_bw() +
theme(axis.line=element_line(colour = "black"),
       panel.grid.major.y = element_line(colour="grey75", linetype="dotted"),
       panel.grid.major.x = element_line(colour="grey75", linetype="dotted"),
       panel.border=element_blank(),
       legend.background=element_rect(fill="grey80", colour="black"),
       legend.title = element_text(size= 10),
       legend.text = element_text(size= 8),
       legend.position="bottom") +

  facet_wrap(~Tipo, scale= "free")

在此处输入图像描述


推荐阅读