Home > Net >  Question on drawing two scales dummy facet plot in R
Question on drawing two scales dummy facet plot in R

Time:10-22

I'm quite new to R.

I try to follow the instructions of this script to draw two scales dummy facet plot in R (two facet plot with three group

But I only get the plot like this.

plot with R

I attached my code here.

library(lubridate)
library(dplyr)
library(ggplot2)

j <- structure(list(name = c(3, 5, 10, 2), urban_P = c(0.00586510263929619, 
        0.00854700854700855, 0.0104712041884817, 0.0161812297734628), 
            cropland_P = c(0.870967741935484, 0.653846153846154, 0.795811518324607, 
            0.841423948220065), natural_P = c(0.12316715542522, 0.337606837606838, 
            0.193717277486911, 0.142394822006472), U_20y = c(0, 0, 0, 
            0.666666666666667), C_20y = c(0.027681660899654, 0.100719424460432, 
            0.0857142857142857, 0.0116731517509728), N_20y = c(-0.288135593220339, 
            -0.300884955752212, -0.327272727272727, -0.153846153846154
            )), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame"
        ))


a <- j %>% pivot_longer(cols = urban_P:natural_P, names_to = "landcover", values_to = "area_percent") 
dt <- a %>% pivot_longer(cols = U_20y:N_20y, names_to = "change", values_to = "rate_20y")

dtF <- rbind(data.frame(
          location = dt$name, 
          num = dt$rate_20y,
          group = dt$change, 
          what = "rate_20y"),
             data.frame(
          location = dt$name, 
          num = dt$area_percent, 
          group = dt$landcover, 
          what = "area_percent")
       )

secondFacet <- FALSE # see below

ggplot(data = dtF, mapping = aes(x = location, y = num,fill=group))  
  facet_grid(what~., scale = "free")  
  geom_bar(data = dtF[dtF$what == "area_percent", ], stat = "identity")  
  geom_line(data = dtF[dtF$what == "rate_20y",], size = 2)   
  scale_y_continuous(name = NULL, labels = function(b) {
      if(!secondFacet) {
        secondFacet <<- TRUE # this is a little cray (and relies on dtF seq = facet seq; works though)
        return(paste0(round(b * 100, 0), "%"))
      } else {
        return(b)
      }
    }
  )

Thanks in advance for any help!!!

CodePudding user response:

Change

ggplot(data = dtF, mapping = aes(x = location, y = num,fill=group))

in

ggplot(data = dtF, mapping = aes(x = location, y = num, fill=group, color=group))
  • Related