0

我正在尝试使用ggplot2包绘制一条线和一个条形图,但使用函数时似乎很难获得两个不同的 y 轴facet_grid()......

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

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

图片

4

1 回答 1

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) 

在此处输入图像描述

于 2016-06-03T16:16:41.410 回答