按主题选项将项添加到图例

时间:2017-07-10 13:40:30

标签: r ggplot2 themes legend

我有一个像这样的数据框:

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"))

我使用库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))

这是目前的情节 enter image description here

我想在传奇中添加&#34;类型&#34;的信息。包含在数据框d中。 我想在图例中有一个新项目,颜色为红色= Reactome,颜色为黑色= KEGG

2 个答案:

答案 0 :(得分:2)

不是说这是一个好主意,但你可以添加一个荒谬的geom来强制添加指南:

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可能无法与您的实际数据一起使用,您可能找不到合适的“荒谬”geom。我同意@ zx8754,一个方面会更清楚:

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')

答案 1 :(得分:1)

您可以使用annotate完成此操作,但它有点手动。

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