[英]How put two graphs into one plot?
我有以下數據集:
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 ))
我想創建一個繪圖,其中條形圖在左側Company 1上描繪“ before”和“ after”值。 同時,公司2的“之前”和“之后”值位於圖的右側。 因此,在y軸上應為變量“值”,但在x軸上應為“前”和“后”兩次,因為公司1在左側,公司2在右側。
我嘗試了以下代碼:
ggplot(data=a, aes(time,company,group=interaction(company, time)))+
geom_col(aes(y=value))
不幸的是,它只產生“之前”和“之后”時間段的變量“值”之和,而忽略公司名稱。
將其作為兩個單獨的圖進行處理,然后使用grid.arrange()會比在一個圖中最初對其進行簡單繪制要占用更多的空間。
當我想像這樣拆分圖時,我使用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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.