代码之家  ›  专栏  ›  技术社区  ›  Víctor Romero

堆积面积图每个元素在上一个元素的顶部

  •  0
  • Víctor Romero  · 技术社区  · 6 年前

    library(ggplot2)
    library(lubridate)
    theme_set(theme_bw())
    
    df <- economics[, c("date", "psavert", "uempmed")]
    df <- df[lubridate::year(df$date) %in% c(1967:1981), ]
    
    # labels and breaks for X axis text
    brks <- df$date[seq(1, length(df$date), 12)]
    lbls <- lubridate::year(brks)
    
    # plot
    ggplot(df, aes(x=date)) + 
    geom_area(aes(y=psavert+uempmed, fill="psavert")) + 
    geom_area(aes(y=uempmed, fill="uempmed")) + 
    labs(title="Area Chart of Returns Percentage", 
       subtitle="From Wide Data format", 
       caption="Source: Economics", 
       y="Returns %") +  # title and caption
    
    scale_x_date(labels = lbls, breaks = brks) +  # change to monthly ticks and labels
    scale_fill_manual(name="", 
                    values = c("psavert"="#00ba38", "uempmed"="#f8766d")) +  # line color
    theme(panel.grid.minor = element_blank())  # turn off minor grid
    

    enter image description here

    然而,这段代码需要事先知道用于填充的不同元素,在本例中是psavert和uempmed。有没有任何方法可以显示一组动态的元素堆叠在一起而不会在y轴上发生碰撞?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Gregor Thomas    6 年前

    ggplot tidyr::gather 为了将数据转换成长格式,绘图就简化了,我们可以在不改变绘图代码的情况下拥有任意多个变量:

    df_long = tidyr::gather(df, "var", "value", -date)
    head(df_long)
    # # A tibble: 6 x 3
    #   date       var     value
    #   <date>     <chr>   <dbl>
    # 1 1967-07-01 psavert  12.5
    # 2 1967-08-01 psavert  12.5
    # 3 1967-09-01 psavert  11.7
    # 4 1967-10-01 psavert  12.5
    # 5 1967-11-01 psavert  12.5
    # 6 1967-12-01 psavert  12.1
    

    请注意,我们现在为 y var geom_area 图层。如果有两个以上的变量 变量

    # plot
    ggplot(df_long, aes(x = date)) +
      geom_area(aes(y = value, fill = var)) +
      labs(
        title = "Area Chart of Returns Percentage",
        subtitle = "From Wide Data format",
        caption = "Source: Economics",
        y = "Returns %"
      ) + 
      scale_x_date(labels = lbls, breaks = brks) +  # change to monthly ticks and labels
      scale_fill_manual(name="", 
                    values = c("psavert"="#00ba38", "uempmed"="#f8766d")) +  # line color
      theme(panel.grid.minor = element_blank())  # turn off minor grid
    

    作为旁注,我建议使用代码注释来(a)解释 为什么? 你做事,以及(b)记录你做事的任何不寻常或棘手的方式。我想你会发现更明显的评论 # title and caption title = "Area Chart of Returns Percentage"

    推荐文章