带有facet_grid的ggplot2图的两个Y轴

时间:2016-06-03 15:01:33

标签: r ggplot2 facet-grid

我试图使用ggplot2包绘制一条线和一个短信,但在使用facet_grid()函数时似乎很难得到两个不同的y轴。

我想在当前的情节中添加一个条形图,其中包含数据框中每个产品的频率(变量Freq)。 任何帮助都会非常棒!!

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

Image

1 个答案:

答案 0 :(得分:1)

另一种方法是使用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) 

enter image description here