【问题标题】:How to get multiple bar plots in R如何在R中获得多个条形图
【发布时间】:2019-12-04 19:43:39
【问题描述】:

数据如下

df1<-read.table(text=" Fruit1 Fruit2 Frut3 Z1   Z2  Z3  ZQ1 ZQ2 ZQ3
A   A   A   A   A   N   N   A   A
B   A   B   N   A   N   N   A   A
C   D   A   A   N   A   N   A   A
D   C   A   A   N   N   N   A   N
B   A   A   A   A   N   N   N   A
B   C   B   N   N   A   N   N   N
A   C   D   N   A   N   A   N   A
D   B   D   A   N   A   N   N   N
A   A   C   A   N   N   N   A   N",header=TRUE)

我想同时拥有三个地块,即 Z1 和 ZQ1 与 Fruit1、Z2 和 ZQ2 与 Fruit2 和 Z3 和 ZQ3 与 Fruit3。 我想像这样同时获得三个图表:

我用过地图,但它不起作用:

map2(names(df1)[4:6],(df1)[7:9], names(df1)[1:3], ~
                   ggplot(df1, aes_string(x = .x, fill = .y)) + 
                   geom_bar(position = position_dodge()))

我们可以在 R 中做到吗?

【问题讨论】:

  • 有人可以帮忙解答这个问题吗?

标签: r ggplot2 bar-chart


【解决方案1】:

试试 egg 包中的 ggarrange() 命令

【讨论】:

  • 我做了,它不起作用。如果它对你有用,你能告诉我吗?
【解决方案2】:

我不完全确定我的解决方案是否是您正在寻找的,但我认为它可能非常接近。我使用 tidyr、stringr 和 dplyr 重新编码了一些变量,以便将 geom_col 与 facet_wrap 一起使用。

library(ggplot2)
library(tidyr)
library(dplyr)
library(stringr)

#Your df
df1<-read.table(text=" Fruit1 Fruit2 Fruit3 Z1   Z2  Z3  ZQ1 ZQ2 ZQ3
A   A   A   A   A   N   N   A   A
B   A   B   N   A   N   N   A   A
C   D   A   A   N   A   N   A   A
D   C   A   A   N   N   N   A   N
B   A   A   A   A   N   N   N   A
B   C   B   N   N   A   N   N   N
A   C   D   N   A   N   A   N   A
D   B   D   A   N   A   N   N   N
A   A   C   A   N   N   N   A   N",header=TRUE)

#Change from wide to long format using tidyr
df2<-gather(df1)

#Make a data frame extracting the letters and numbers of the key column (Fruit, Z, ZQ 
#and 1, 2, 3) using stringr
 df2<-data.frame(panel = str_extract(df2$key,"[1-9]"),
            factor = str_extract(df2$key,"[A-z]+"),
            df2)

 #frequency of each letter per panel variable (1,2,3) and factor (Fruit, Z and ZQ)
 df2<-df2 %>% 
   group_by(panel,factor) %>%
   count(value)

 #Make geom_col with a facet_wrap using panel and factor variables
 ggplot(df2,aes(x=value,y=n,fill=value)) + 
  geom_col() +
  facet_wrap(~panel*factor)

【讨论】:

    猜你喜欢
    • 2012-02-12
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 2020-09-11
    相关资源
    最近更新 更多