3

2 つの凡例を含む ggplot2 によって生成されたプロットがあります。凡例の配置が理想的ではないので、調整したいと思います。「ggplotで2つの凡例を個別に配置するにはどうすればよいですか」への回答に示されている方法を模倣しようとしてい ます。その回答に示されている例は機能します。ただし、説明されている方法を自分の状況で機能させることはできません。

Debian スクイーズで R 2.15.3 (2013-03-01)、ggplot2_0.9.3.1、lattice_0.20-13、gtable_0.1.2、gridExtra_0.9.1 を使用しています。

によって生成されたプロットを考えてみましょうminimal.R。これは私の実際のプロットに似ています。

########################
minimal.R
########################

get_stat <- function()
  {
    n = 20
    q1 = qnorm(seq(3, 17)/20, 14, 5)
    q2 = qnorm(seq(1, 19)/20, 65, 10)
    Stat = data.frame(value = c(q1, q2),
      pvalue = c(dnorm(q1, 14, 5)/max(dnorm(q1, 14, 5)), d = dnorm(q2, 65, 10)/max(dnorm(q2, 65, 10))),
      variable = c(rep('true', length(q1)), rep('data', length(q2))))
    return(Stat)
  }

stat_all<- function()
{
  library(ggplot2)
  library(gridExtra)
  stathuman = get_stat()
  stathuman$dataset = "human"
  statmouse = get_stat()
  statmouse$dataset = "mouse"
  stat = merge(stathuman, statmouse, all=TRUE)
  return(stat)
}

simplot <- function()
  {
    Stat = stat_all()
    Pvalue = subset(Stat, variable=="true")
    pdf(file = "CDF.pdf", width = 5.5, height = 2.7)
    stat = ggplot() + stat_ecdf(data=Stat, n=1000, aes(x=value, colour = variable)) +
      theme(legend.key = element_blank(), legend.background = element_blank(), legend.position=c(.9, .25), legend.title = element_text(face = "bold")) +
        scale_x_continuous("Negative log likelihood") +
          scale_y_continuous("Proportion $<$ x") +
            facet_grid(~ dataset, scales='free') +
              scale_colour_manual(values = c("blue", "red"), name="Data type",
                                  labels=c("Gene segments", "Model"), guide=guide_legend(override.aes = list(size = 2))) +
                geom_area(data=Pvalue, aes(x=value, y=pvalue, fill=variable), position="identity", alpha=0.5) +
                  scale_fill_manual(values = c("gray"), name="Pvalue", labels=c(""))
    print(stat)
    dev.off()
  }

simplot()

これにより、次のプロットが得られます。ご覧のとおり、Data type とのPvalue凡例は適切に配置されていません。このコードを に変更しました minimal2.R

ここに画像の説明を入力

バージョン 1 では、凡例を一番上に配置する必要があり、コードはエラーなしで実行されますが、凡例は表示されません。

編集: 2 つのボックスが上下に表示されます。上の方は空白です。grid.arrange()@baptiste で提案されているように、高さを設定しないと、凡例とプロットの両方が下のボックスに配置されます。図のように高さを設定すると、凡例が表示されません。

EDIT2:grid.newpage以前の質問からコピーした余分な空白のボックスがによって呼び出されたようです。なぜそこにあったのかわかりません。その行を使用しない場合は、1 つのボックス/ページだけが表示されます。

バージョン 2 では、このエラーが発生します。

Error in UseMethod("grid.draw") :
  no applicable method for 'grid.draw' applied to an object of class "c('gg', 'ggplot')"
Calls: simplot -> grid.draw

編集: print(plotNew)@baptisteの提案に従って使用すると、次のエラーが表示されます

Error in if (empty(data)) { : missing value where TRUE/FALSE needed 
Calls: simplot ... facet_map_layout -> facet_map_layout.grid -> locate_grid.

ここで何が起こっているのかを理解しようとしましたが、関連する情報はあまり見つかりませんでした。

ノート:

  1. 経験的CDFで階段効果が得られる理由がわかりません。明確な説明があると確信しています。ご存知でしたら教えてください。

  2. 私が真剣に実験したことのない matplotlib などの代替案を誰かが提案できる場合は、このコードの代替案、さらにはこのグラフを生成するための ggplot2 を検討するつもりです。

  3. 追加する

    print(ggplot_gtable(ggplot_build(stat2)))
    

    minimal2.R私に与える

    TableGrob (7 x 7) "layout": 12 grobs
        z     cells       name                                 grob
    1   0 (1-7,1-7) background       rect[plot.background.rect.186]
    2   1 (3-3,4-4)  strip-top absoluteGrob[strip.absoluteGrob.135]
    3   2 (3-3,6-6)  strip-top absoluteGrob[strip.absoluteGrob.141]
    4   5 (4-4,3-3)     axis-l  absoluteGrob[GRID.absoluteGrob.129]
    5   3 (4-4,4-4)      panel                gTree[GRID.gTree.155]
    6   4 (4-4,6-6)      panel                gTree[GRID.gTree.169]
    7   6 (5-5,4-4)     axis-b  absoluteGrob[GRID.absoluteGrob.117]
    8   7 (5-5,6-6)     axis-b  absoluteGrob[GRID.absoluteGrob.123]
    9   8 (6-6,4-6)       xlab          text[axis.title.x.text.171]
    10  9 (4-4,2-2)       ylab          text[axis.title.y.text.173]
    11 10 (4-4,4-6)  guide-box                    gtable[guide-box]
    12 11 (2-2,4-6)      title            text[plot.title.text.184]
    

    この内訳がわかりません。誰でも説明できますか?は伝説に対応しており、どの guide-boxようにしてこれを知ることができますか?

これが私のコードの修正版ですminimal2.R

########################
minimal2.R
########################

get_stat <- function()
  {
    n = 20
    q1 = qnorm(seq(3, 17)/20, 14, 5)
    q2 = qnorm(seq(1, 19)/20, 65, 10)
    Stat = data.frame(value = c(q1, q2),
      pvalue = c(dnorm(q1, 14, 5)/max(dnorm(q1, 14, 5)), d = dnorm(q2, 65, 10)/max(dnorm(q2, 65, 10))),
      variable = c(rep('true', length(q1)), rep('data', length(q2))))
    return(Stat)
  }

stat_all<- function()
{
  library(ggplot2)
  library(gridExtra)
  library(gtable)
  stathuman = get_stat()
  stathuman$dataset = "human"
  statmouse = get_stat()
  statmouse$dataset = "mouse"
  stat = merge(stathuman, statmouse, all=TRUE)
  return(stat)
}

simplot <- function()
  {
    Stat = stat_all()
    Pvalue = subset(Stat, variable=="true")
    pdf(file = "CDF.pdf", width = 5.5, height = 2.7)

    ## only include data type legend
    stat1 = ggplot() + stat_ecdf(data=Stat, n=1000, aes(x=value, colour = variable)) +
      theme(legend.key = element_blank(), legend.background = element_blank(), legend.position=c(.9, .25), legend.title = element_text(face = "bold")) +
        scale_x_continuous("Negative log likelihood") +
          scale_y_continuous("Proportion $<$ x") +
            facet_grid(~ dataset, scales='free') +
              scale_colour_manual(values = c("blue", "red"), name="Data type", labels=c("Gene segments", "Model"), guide=guide_legend(override.aes = list(size = 2))) +
                geom_area(data=Pvalue, aes(x=value, y=pvalue, fill=variable), position="identity", alpha=0.5) +
                  scale_fill_manual(values = c("gray"), name="Pvalue", labels=c(""), guide=FALSE)

    ## Extract data type legend
    dataleg <- gtable_filter(ggplot_gtable(ggplot_build(stat1)), "guide-box")

    ## only include pvalue legend
    stat2 = ggplot() + stat_ecdf(data=Stat, n=1000, aes(x=value, colour = variable)) +
      theme(legend.key = element_blank(), legend.background = element_blank(), legend.position=c(.9, .25), legend.title = element_text(face = "bold")) +
        scale_x_continuous("Negative log likelihood") +
          scale_y_continuous("Proportion $<$ x") +
            facet_grid(~ dataset, scales='free') +
              scale_colour_manual(values = c("blue", "red"), name="Data type", labels=c("Gene segments", "Model"), guide=FALSE) +
                geom_area(data=Pvalue, aes(x=value, y=pvalue, fill=variable), position="identity", alpha=0.5) +
                  scale_fill_manual(values = c("gray"), name="Pvalue", labels=c(""))

    ## Extract pvalue legend
    pvalleg <- gtable_filter(ggplot_gtable(ggplot_build(stat2)), "guide-box")

    ## no legends
    stat = ggplot() + stat_ecdf(data=Stat, n=1000, aes(x=value, colour = variable)) +
      theme(legend.key = element_blank(), legend.background = element_blank(), legend.position=c(.9, .25), legend.title = element_text(face = "bold")) +
        scale_x_continuous("Negative log likelihood") +
          scale_y_continuous("Proportion $<$ x") +
            facet_grid(~ dataset, scales='free') +
              scale_colour_manual(values = c("blue", "red"), name="Data type", labels=c("Gene segments", "Model"), guide=FALSE) +
                geom_area(data=Pvalue, aes(x=value, y=pvalue, fill=variable), position="identity", alpha=0.5) +
                  scale_fill_manual(values = c("gray"), name="Pvalue", labels=c(""), guide=FALSE)

    ## Add data type legend: version 1 (data type legend should be on top)
    ## plotNew <- arrangeGrob(dataleg, stat, heights = unit.c(dataleg$height, unit(1, "npc") - dataleg$height), ncol = 1)

    ## Add data type legend: version 2 (data type legend should be somewhere in the interior)
    ## plotNew <- stat + annotation_custom(grob = dataleg, xmin = 7, xmax = 10, ymin = 0, ymax = 4)

    grid.newpage()
    grid.draw(plotNew)
    dev.off()
  }

simplot()
4

1 に答える 1

2

grid.arrangeとarrangeGrobでできますが、高さと幅を正しく調整するのは面倒です。

grid.arrange(arrangeGrob(dataleg, pvalleg, nrow=1, ncol=2, widths=c(unit(1, "npc"), unit(5, "cm"))), stat, nrow=2, heights=c(unit(.2, "npc"), unit(.8, "npc")))

私は通常、適切な凡例を使用して新しいプロットを作成し、この新しい凡例を使用することを好みます。

 h <- ggplot(data.frame(a=rnorm(10), b=rnorm(10), c=factor(rbinom(10, 1,.5), labels=c("Gene segments", "Model")), d=factor("")), 
        aes(x=a, y=b)) +
   geom_line(aes(color=c), size=1.3) + geom_polygon(aes(fill=d)) +
   scale_color_manual(values=c("blue", "red"), name="Data type") + 
   scale_fill_manual(values="gray", name="P-value") 
 g_legend<-function(a.gplot){
   tmp <- ggplot_gtable(ggplot_build(a.gplot))
   leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
   legend <- tmp$grobs[[leg]]
   return(legend)
 }
 legend <- g_legend(h)

 grid.arrange(stat, legend, nrow=1, ncol=2, widths=c(unit(.8, "npc"), unit(.2, "npc")))
 grid.arrange(legend, stat, nrow=2, ncol=1, heights=c(unit(.2, "npc"), unit(.8, "npc")))
于 2013-07-04T12:27:46.537 に答える