【问题标题】:How put two graphs into one plot?如何将两张图放在一张图中?
【发布时间】:2019-07-12 16:51:58
【问题描述】:

我有以下数据集:

a<-data.frame(time=c("before","after","before","after"),
                  company=c(1,1,2,2),
                  value=c(3.751522,4.776224,3.838707,2.644144 ))

我想创建一个图,其中条形图在左侧公司 1 上描绘了“之前”和“之后”的值。同时公司 2 的“之前”和“之后”值在图的右侧。 因此,y 轴上应该是变量“值”,但 x 轴上应该是“之前”和“之后”2 次,因为左侧是公司 1,右侧是公司 2。

我尝试了以下代码:

ggplot(data=a, aes(time,company,group=interaction(company, time)))+
  geom_col(aes(y=value))

不幸的是,它只在“之前”和“之后”的时间段内产生变量“价值”的总和,而忽略了公司名称。

将其作为两个单独的图然后使用 grid.arrange() 将比最初在一个图中简单地绘制更多空间。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    当我想像这样拆分图表时,我使用 facet_grid 参数。

    library(tidyverse)
    
    a<-data.frame(time=c("before","after","before","after"),
                  company=c(1,1,2,2),
                  value=c(3.751522,4.776224,3.838707,2.644144 ))
    
    ggplot(data=a, 
           aes(x = time %>%
                     # set time as factor to set order of before, after
                     factor(levels = c("before", "after")),
               y = value))+
      geom_col()+
      # split graph by company
      facet_grid(cols = vars(company))
    

    resulting graph image

    【讨论】:

      【解决方案2】:

      x是公司与时间的交互,y是价值。我认为您不需要为此在geom_col() 中添加任何参数。

      ggplot(data=a, aes(x=interaction(time, company),y=value,fill=interaction(time, company)))+
        geom_col()
      

      甚至更好:

      a$company<-as.factor(a$company)
      ggplot(a, aes(x=company, y=value, fill=time)) + geom_col(position="dodge")
      

      【讨论】:

        猜你喜欢
        • 2012-03-09
        • 2021-03-28
        • 2022-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-22
        • 2022-01-19
        • 1970-01-01
        相关资源
        最近更新 更多