微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用ggplot在R中创建不均匀的facet_wrap网格?

如何解决如何使用ggplot在R中创建不均匀的facet_wrap网格?

我目前正在R中使用ggplot2进行图形处理,我想使用facet_wrap创建5个子图。

到目前为止,这是我的代码

# getting the data
data = structure(list(type = c("red","blue","orange","yellow","green","red","green"),cond = c("new","new","old","old"),fact = c("light","light","shiny","shiny"),score = c(2L,4L,8L,6L,10L,3L,5L,9L,1L,12L,14L,18L,16L,20L,13L,15L,19L,11L,13L)),class = "data.frame",row.names = c(NA,-20L))

library(ggplot2)

ggplot(data=data,aes(x=cond,y=score,fill=fact)) +
  geom_bar(stat="identity",position=position_dodge()) +
  theme_bw() + facet_wrap(. ~ type,ncol=3) 

这将创建以下图:

what it looks like now

但是,由于一种颜色比其他颜色重要得多,因此我想创建以下一种颜色:

desired options

有人知道如何让facet_wrap做到这一点,还是可以将我指向另一个创建它的选项?

干杯, 最高

解决方法

这是将patchwork和构面混合在一起的方法。

blue创建一个图,为其他所有图。从蓝色图中删除图例,并从另一个图中删除y轴标题。

library(tidyverse)
library(patchwork)

p_other <-
  data %>%
  filter(type != "blue") %>%
  ggplot(aes(x = cond,y = score,fill = fact)) +
    geom_bar(stat = "identity",position = position_dodge()) +
    theme_bw() +
    facet_wrap(. ~ type,ncol = 2) +
    theme(axis.title.y = element_blank())

p_blue <-
  data %>%
  filter(type == "blue") %>%
  ggplot(aes(x = cond,ncol = 2) +
    theme(legend.position = "none")

使用|添加来自拼凑而成的列。

(p_blue | p_other) + plot_layout(widths = c(1,2))

plot

,

尝试使用patchwork的这种方法,您将必须格式化type变量以进行分解,以便具有所需的顺序,然后对绘图使用函数。之后,您可以组成所需的绘图。我已经为您设计了功能,这属于您问题中的选项2。这里的代码:

library(ggplot2)
library(patchwork)
#Data format
data$type <- factor(data$type,levels = c("blue","green","orange","red","yellow"),ordered = T)

我们为数据创建一个列表:

#Create list
List <- split(data,data$type)

现在,用于绘图的功能:

#Create isolate plots
myplot <- function(x)
{
  text <- unique(as.character(x$type))
  #Plot
  G <- ggplot(data=x,aes(x=cond,y=score,fill=fact)) +
    geom_bar(stat="identity",position=position_dodge()) +
    theme_bw() + ggtitle(text)+
    theme(plot.title = element_text(hjust=0.5))
  return(G)
}

然后,我们开始构建地块:

#Plot for only first plot
P1 <- myplot(List[[1]])
P2 <- wrap_plots(lapply(List[-1],myplot),ncol = 2)

最后,我们安排地块:

#Now wrap plots
P3 <- P1 + P2
P4 <- P3 +  plot_layout(guides = 'collect')

输出:

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。