簡體   English   中英

帶有facet_grid的ggplot2圖的兩個Y軸

[英]two Y-axis for ggplot2 graph with a facet_grid

我正在嘗試使用ggplot2包繪制一條線和一個barchat,但使用facet_grid()函數時似乎很難獲得兩個不同的y軸...

我想在數據圖中添加一個條形圖,其中包含每個產品的頻率(可變頻率)。 任何幫助都將非常棒!

temp = data.frame(Product=as.factor(c("L","P","41","43")),
              Freq = c(0.2,0.8,0.7,0.3),
              rate = c(14,17,12,20),
              var= c("QUAL","QUAL","OCCU","OCCU"))

temp %>%  ggplot() + theme_grey(base_size=20) + 
geom_line(aes(x=Product, y=rate, group=var))+  
geom_point(aes(x=Product, y=rate, group=var))+ 
geom_label( aes(x=Product,y=rate,label=paste0(rate,"%") ))  +
  facet_grid(.~ var, scales = "free") +
 theme(legend.position="none", axis.text.x=element_text(angle=45, vjust=0.1)) -> p2

圖片

一種替代方法是使用grid.arrange{gridExtra}

library(gridExtra)

### 1. create a plot function

plotfunc <- function(Data, xxx , ymin, ymax) {

   ggplot(data=subset(temp, var==xxx)) + theme_grey(base_size=20) + 
    geom_line(aes(x=Product, y=rate, group=var))+  
    geom_point(aes(x=Product, y=rate, group=var))+ 
    geom_label( aes(x=Product,y=rate,label=paste0(rate,"%") ))  +
    facet_grid(.~ var, scales = "free") +
    theme(legend.position="none", axis.text.x=element_text(angle=45, vjust=0.1)) +
    ylim(ymin, ymax) 
    } 

### 2. Generate the plots with different axis limits
occuplot <- plotfunc(temp, "OCCU", 10, 20)
qualplot <- plotfunc(temp, "QUAL", 12, 18)

### 3. Arrange the separate plots into one single chart
grid.arrange( occuplot, qualplot, nrow=1, ncol=2) 

在此處輸入圖片說明

暫無
暫無

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

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