美文网首页RR学习与可视化可视化专题
sec_axis ggplo2 绘制分面双坐标图

sec_axis ggplo2 绘制分面双坐标图

作者: 热衷组培的二货潜 | 来源:发表于2020-04-29 12:16 被阅读0次

    数据构建来源:

    https://stackoverflow.com/questions/26917689/how-to-use-facets-with-a-dual-y-axis-ggplot

    library(ggplot2)
    
    
    dt.diamonds <- data.table::as.data.table(diamonds)
    
    d1 <- dt.diamonds[,list(revenue = sum(price),
                            stones = length(price)),
                      by = c("clarity","cut")]
    
    
    max_stones <- max(d1$stones)
    max_revenue <- max(d1$revenue)
    
    
    d2 <- gather(d1, 'var', 'val', stones:revenue) %>% 
      mutate(val = if_else(var == 'revenue', as.double(val), val / (max_stones / max_revenue)))
    
    ggplot() +
      # 柱状图数据
      geom_bar(data = filter(d2, var == 'revenue'), 
               aes(clarity, val, fill = cut),
               col = "black",
               stat = "identity") +
      # 折线图数据
      geom_line(data = filter(d2, var == 'stones'), aes(clarity, val, group = cut),
                col = "red", size = 1) +
      geom_point(data = filter(d2, var == 'stones'), aes(clarity, val, group = cut),
                col = "blue", size = 2) +
      facet_grid(cut~.) +
      # 对调 xy 轴
      coord_flip() +
      # 绘制第二个 x 轴,且原本的 x 轴放置于最上面
      scale_y_continuous(sec.axis = sec_axis(trans = ~ . * (max_stones / max_revenue),
                                             name = 'number of stones'),
                         labels = scales::dollar,
                         position = "right",
                         expand = c(0, 0)) +
      # 原本的 y 轴放置到最左边
      scale_x_discrete(position = "bottom") +
      theme_bw() +
      theme(panel.background = element_rect(fill = "#F3F2EE", colour = "#F3F2EE"),
            panel.grid.major = element_line(size = 1, linetype = 'solid',
                                            colour = "white"), 
            panel.grid.minor = element_line(size = 1, linetype = 'solid',
                                            colour = "white"),
            axis.text.x = element_text(angle = 0, hjust = 0.5),
            axis.text.y = element_text(color = "blue"),
            # axis.text.y.right = element_text(color = "red"),
            legend.position = "bottom",
            strip.text.y = element_text(angle = 0, color = "black",
                                        face = "bold", size = 12)) +
      labs(x = "")
    

    strip.text.y 用来控制分面后标签文本的具体信息:
    比如上面 strip.text.y 换成

    strip.text.y = element_text(angle = -90, color = "black",
                                        face = "bold", size = 12))
    

    如果我想将标签放在左边,且水平放置呢?

    strip.text.y.left 和 strip.placement 至关重要的参数

    ggplot() +
      # 柱状图数据
      geom_bar(data = filter(d2, var == 'revenue'), 
               aes(clarity, val, fill = cut),
               col = "black",
               stat = "identity") +
      # 折线图数据
      geom_line(data = filter(d2, var == 'stones'), aes(clarity, val, group = cut),
                col = "red", size = 1) +
      geom_point(data = filter(d2, var == 'stones'), aes(clarity, val, group = cut),
                 col = "blue", size = 2) +
      facet_grid(cut~.,
                 switch = "y") +
      # 对调 xy 轴
      coord_flip() +
      # 绘制第二个 x 轴,且原本的 x 轴放置于最上面
      scale_y_continuous(sec.axis = sec_axis(trans = ~ . * (max_stones / max_revenue),
                                             name = 'number of stones'),
                         labels = scales::dollar,
                         position = "right",
                         expand = c(0, 0)) +
      # 原本的 y 轴放置到最左边
      scale_x_discrete(position = "bottom") +
      theme_bw() +
      theme(panel.background = element_rect(fill = "#F3F2EE", colour = "#F3F2EE"),
            panel.grid.major = element_line(size = 1, linetype = 'solid',
                                            colour = "white"), 
            panel.grid.minor = element_line(size = 1, linetype = 'solid',
                                            colour = "white"),
            axis.text.x = element_text(angle = 0, hjust = 0.5),
            axis.text.y = element_text(color = "blue"),
            # axis.text.y.right = element_text(color = "red"),
            legend.position = "bottom",
            strip.background = element_blank(),
            strip.placement  = "outside",
            strip.text.y.left = element_text(angle = 0, color = "black",
                                        face = "bold", size = 12)) +
      labs(x = "")
    

    如果标签文本过才需要换行呢?

    这里给了一个答案:

    How to Fit Long Text into Ggplot2 facet Titles

    解决方案,就在将分面的文本预先用 str_wrap() 函数进行分行处理

    library(reshape2)
    library(ggplot2)
    
    Example<-data.frame(Year,Q1,Q2, stringsAsFactors=FALSE)
    
    ExampleM<-melt(Example,id.vars=c("Year"))
    
    # Helper function for string wrapping. 
    # Default 20 character target width.
    swr = function(string, nwrap=20) {
      paste(strwrap(string, width=nwrap), collapse="\n")
    }
    swr = Vectorize(swr)
    
    # Create line breaks in Year
    ExampleM$Year = swr(ExampleM$Year)
    
    ggplot(ExampleM, aes(x=variable, fill=value)) + 
      geom_bar(position="dodge") + 
      facet_grid(~Year)
    

    相关文章

      网友评论

        本文标题:sec_axis ggplo2 绘制分面双坐标图

        本文链接:https://www.haomeiwen.com/subject/gsegwhtx.html