簡體   English   中英

R ggplot2雙y軸多面環繞,一條直方圖和另一條線

[英]R ggplot2 Dual y-axis facet wrap, one histogram and other line

我有兩個方面包裹的情節, p1p2

p1

在此處輸入圖片說明

p2

在此處輸入圖片說明

如您所見,x軸值在兩個圖中都排成一行,但是y軸值差別很大。 我想將p2疊加到p1上,將p1 y軸保持在左側,並在右側創建另一個p2 y軸。

這就是我現在所擁有的,但是我不確定如何正確組合p1和p2的grob。

library(ggplot2)
library(gtable)
library(grid)

themer <- theme(panel.grid.major = element_blank(), 
                panel.grid.minor = element_blank(), 
                panel.background = element_blank(),
                panel.margin = unit(0, "lines"),
                strip.background = element_rect(fill="#F8F8F8"))

p2 <- ggplot(normaldens, aes(y=density,x=predicted)) + 
        geom_line(color="red") + 
        facet_wrap(~ motif) + 
        labs(title=paste("Methylation Score:",motif_f[j]),x="Methylation Score",y="Density") +
        themer
p1 <- ggplot(dat, aes(x=score)) +
        geom_histogram( binwidth = bin_width,col="red",fill="blue",alpha=0.2) +  
        facet_wrap(~ motif) + 
        labs(title=paste("Methylation Score:",motif_f[j]),x="Methylation Score",y="Counts") +
        themer

###### COMBINE GROBS #######
g1 <- ggplot_gtable(ggplot_build(p1))
g2 <- ggplot_gtable(ggplot_build(p2))

combo_grob <- g2
pos <- length(combo_grob) - 1
combo_grob$grobs[[pos]] <- cbind(g1$grobs[[pos]],
                                 g2$grobs[[pos]], size = 'first')
panel_num <- length(unique(df1$z))
for (i in seq(panel_num))
{
  # grid.ls(g1$grobs[[i + 1]])
  panel_grob <- getGrob(g1$grobs[[i + 1]], 'geom_point.points',
                        grep = TRUE, global = TRUE)
  combo_grob$grobs[[i + 1]] <- addGrob(combo_grob$grobs[[i + 1]], 
                                       panel_grob)
}       


pos_a <- grep('axis_l', names(g1$grobs))
axis <- g1$grobs[pos_a]
for (i in seq(along = axis))
{
  if (i %in% c(2, 4))
  {
    pp <- c(subset(g1$layout, name == paste0('panel-', i), se = t:r))

    ax <- axis[[1]]$children[[2]]
    ax$widths <- rev(ax$widths)
    ax$grobs <- rev(ax$grobs)
    ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.5, "cm")
    ax$grobs[[2]]$x <- ax$grobs[[2]]$x - unit(1, "npc") + unit(0.8, "cm")
    combo_grob <- gtable_add_cols(combo_grob, g2$widths[g2$layout[pos_a[i],]$l], length(combo_grob$widths) - 1)
    combo_grob <- gtable_add_grob(combo_grob, ax,  pp$t, length(combo_grob$widths) - 1, pp$b)
  }
}

pp <- c(subset(g1$layout, name == 'ylab', se = t:r))

ia <- which(g1$layout$name == "ylab")
ga <- g1$grobs[[ia]]
ga$rot <- 270
ga$x <- ga$x - unit(1, "npc") + unit(1.5, "cm")

combo_grob <- gtable_add_cols(combo_grob, g2$widths[g2$layout[ia,]$l], length(combo_grob$widths) - 1)
combo_grob <- gtable_add_grob(combo_grob, ga, pp$t, length(combo_grob$widths) - 1, pp$b)
combo_grob$layout$clip <- "off"

grid.draw(combo_grob)

我得到了這個錯誤,我知道這與我將兩個gtable組合在一起的方式有關。

gList中的錯誤(list(x = 0.5,y = 0.5,width = 1,height = 1,just =“ centre”,:“ gList”中僅允許'grobs'

我不認為您可以在ggplot2做第二個y軸,但是在一個繪圖中同時繪制密度和直方圖並使用條形標記計數(而不是嘗試修改第二個y軸)呢? 這是一個示例(使用內置的iris數據集):

首先,我們將計算密度的最大值並計數,並使用它們來創建比例因子,以編程方式確保直方圖和密度圖具有相同的垂直比例。

library(dplyr) 

# Find maximum value of density
densMax = iris %>% group_by(Species) %>%
  summarise(dens = max(density(Sepal.Length)[["y"]])) %>%
  filter(dens == max(dens))

# Find maximum value of bin count
countMax = iris %>% 
  group_by(Species, 
           bins=cut(Sepal.Length, seq(floor(min(Sepal.Length)),
                                      ceiling(max(Sepal.Length)), 
                                      0.25), right=FALSE)) %>%
  summarise(count=n()) %>% 
  ungroup() %>% filter(count==max(count))

現在我們將直方圖條縮放為密度圖的大小。 sf是比例因子:

ggplot(iris, aes(x=Sepal.Length, sf = countMax$count/densMax$dens)) + 
  geom_histogram(fill=hcl(195,100,65), colour="grey50", binwidth=0.25) +
  geom_density(colour="red", aes(y=..density.. * sf)) +
  facet_wrap(~ Species) + 
  themer

在此處輸入圖片說明

或者,您可以朝另一個方向前進,然后將密度圖縮放為直方圖:

# Scale histogram bars to size of density plot
ggplot(iris, aes(x=Sepal.Length, sf = densMax$dens/countMax$count)) + 
  geom_histogram(aes(y=..count..*sf), 
                 fill=hcl(195,100,65), colour="grey50", binwidth=0.25) +
  stat_bin(aes(label=..count.., y=..count..*0.5*sf), 
           geom="text", size=4, color="white", binwidth=0.25) +
  geom_density(colour="red") +
  facet_wrap(~ Species) + 
  themer +
  labs(y="Density")

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM