簡體   English   中英

將ggplot2圖放置在網格中並具有1個圖例

[英]Placing ggplot2 plots in a grid and having 1 legend

我有以下代碼生成了k=2類圖的列表。

library(ggplot2)
library(cumplyr)
library(scales)
library(reshape2)
library(RColorBrewer)
library(tools)
library(gridExtra)

jet.colors <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan","#7FFF7F", "yellow", "#FF7F00", "red", "#7F0000"))
myPalette <- colorRampPalette(rev(brewer.pal(11, "Spectral")))

x   = 1:50
y   = 1:50
pts = cartesian_product(c('x','y'))


make_df <- function(i) {
    k = if(i <= 5) 1 else 2
    d1 = cbind(pts, runif(nrow(pts),min=0,max=10*i), 1)
    colnames(d1) = c("x","y","val", "k")
    return(d1)
}

dflist = lapply(as.list(1:10),make_df)


make_plot <- function(data, gmin = 0, gmax = 100) {
    p1 <- ggplot(data)
    p1 <- p1 + geom_tile(aes(x = x, y = y, fill = val))
    p1 <- p1 + scale_fill_gradientn(colours = myPalette(gmax), limits=c(gmin,gmax))
    return(p1)
}

plotlist = lapply(dflist, make_plot)
g = do.call(arrangeGrob, plotlist)

我在情節的最后安排上遇到了麻煩。 這些圖可以是k = 1類型或k = 2類型。我想:

  • 將地塊排列在2 x 5的網格中,
  • 只有1個傳說
  • 用適當的k值標記繪圖的每一行
  • 使行上的圖彼此靠近,也許彼此之間只有很小的距離

我已經為此轉動了幾個小時,但無濟於事!

謝謝!

這就是我對facet_wrap (在這種情況下,grid並沒有什么意義):

ggplot(df, aes(x=x, y=y, fill=val)) + 
  geom_tile() + 
  scale_fill_gradientn(colours = myPalette(100), limits=c(0,100)) +
  facet_wrap(~ k, nrow=2) +
  theme(axis.text.x=element_text(angle=90))

產生:

在此處輸入圖片說明

我也不得不修改您的代碼:

make_df <- function(i) {
  k = if(i <= 5) 1 else 2
  d1 = cbind(pts, runif(nrow(pts),min=0,max=10*i), i)  # I think you want the last value to be `i`, but I'm guessing
  colnames(d1) = c("x","y","val", "k")
  return(d1)
}
pts = expand.grid(x, y)  # cartesian_product() didn't work for me, but I think this is equivalent
dflist = lapply(as.list(1:10),make_df)
df <- do.call(rbind, dflist)

如果各列表示某些含義,則可以執行以下操作

library(ggplot2)

nplot = 10

# assume that the first 5 are of the same group, and last 5 are of the same group
dlist = lapply(1:10, function(i){
    x = rnorm(100)
    y = rnorm(100)
    p = i*(i<=5)+(i-5)*(i>5)
    k = 1*(i<=5)+2*(i>5)
    data.frame(x,y,p,k)
})

# create a large dataframe
D = do.call(rbind, dlist)
ggplot(D, aes(x=x,y=y)) + geom_point() + facet_grid(k~p) 

ggplot

暫無
暫無

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

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