1

I have a data frame d like this:

d <- data.frame("name" = c("pippo","pluto","paperino"), 
"id" = c(1,2,3),"count" = c(10,20,30),
"pvalue"=c(0.01,0.02,0.05),
geneRatio=c(0.5,0.8,0.2),
type=c("KEGG","Reactome","Reactome"))

and I plot a dotplot using the library ggplot:

   ggplot(data = d,aes(geneRatio,name,size=count,colour = pvalue)) + 
   geom_point()+ 
   ggtitle("Significantly Pathways") + 
   xlab("Gene Ratio") + 
   ylab("Pathways")+ 
   theme(axis.text.y = element_text(color=d$type))

This is the plot at the moment enter image description here

I would like to add to legend the information of "type" contained in dataframe d. I would like to have a new item in the legend with color red = Reactome and color black= KEGG

zx8754
  • 52,746
  • 12
  • 114
  • 209
TheAvenger
  • 458
  • 1
  • 6
  • 19

2 Answers2

2

Not saying that this is a good idea, but you can add a nonsensical geom to force the adding of a guide:

d <- data.frame("name" = c("pippo","pluto","paperino"), 
                "id" = c(1,2,3),
                "count" = c(10,20,30),
                "value"=c(0.01,0.02,0.05),
                geneRatio=c(0.5,0.8,0.2),
                type=c("KEGG","Reactome","Reactome")
                )

library(ggplot2)

ggplot(data = d, aes(geneRatio,name,colour = pvalue)) + 
    geom_point(aes(size=count))+ 
    geom_polygon(aes(geneRatio,name,fill = type)) +
    ggtitle("Significantly Pathways") + 
    xlab("Gene Ratio") + 
    ylab("Pathways") + 
    scale_fill_manual(values = c('Reactome'='red', 'KEGG'='black')) +
    theme(axis.text.y = element_text(color=d$type))

geom_polygon may not work with your actual data, and you may not find a suitable 'nonsensical' geom. I agree with @zx8754, a facet would be clearer:

ggplot(data = d, aes(geneRatio,name,colour = pvalue)) + 
    geom_point(aes(size=count)) + 
    ggtitle("Significantly Pathways") + 
    xlab("Gene Ratio") + 
    ylab("Pathways") + 
    facet_grid(type ~ ., scales = 'free_y', switch = 'y')

GGamba
  • 13,140
  • 3
  • 38
  • 47
1

You could accomplish this using annotate, but it is a bit manual.

ggplot(data = d, aes(geneRatio, name, size = count, colour = pvalue)) + 
  geom_point() + 
  ggtitle("Significantly Pathways") + 
  xlab("Gene Ratio") + 
  ylab("Pathways")+ 
  theme(axis.text.y = element_text(color=d$type)) +
  annotate("text", x = 0.25, y = 3.5, label = "Reactome", color = "red") +
  annotate("text", x = 0.25, y = 3.4, label = "KEGG", color = "black")

enter image description here

Eric Watt
  • 3,180
  • 9
  • 21