【问题标题】:Line plot with bars in secondary axis with different scales in ggplot2在 ggplot2 中具有不同比例的次轴条形线图
【发布时间】:2020-09-03 12:30:49
【问题描述】:

我正在尝试绘制折线图(数据点介于 0 和 2.5 之间,间隔为 0.5)。我想在右侧轴上的同一图表中绘制一些条形图(0 到 60 之间,间隔为 10)。我在代码中犯了一些错误,以至于条形图绘制在左侧轴上。

以下是一些示例数据和代码:

Month <- c("J","F","M","A")
Line <- c(2.5,2,0.5,3.4)
Bar <- c(30,33,21,40)
df <- data.frame(Month,Line,Bar)

ggplot(df, aes(x=Month)) +
  geom_line(aes(y = Line,group = 1)) +
  geom_col(aes(y=Bar))+
  scale_y_continuous("Line",
                     sec.axis = sec_axis(trans= ~. /50, name = "Bar"))

Here's the output

提前致谢。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    使用缩放因子尝试这种方法。最好在变量之间使用比例因子,然后将其用于第二个 y 轴。我对您的代码做了些微改动:

    library(tidyverse)
    #Data
    Month <- c("J","F","M","A")
    Line <- c(2.5,2,0.5,3.4)
    Bar <- c(30,33,21,40)
    df <- data.frame(Month,Line,Bar)
    #Scale factor
    sfactor <- max(df$Line)/max(df$Bar)
    #Plot
    ggplot(df, aes(x=Month)) +
      geom_line(aes(y = Line,group = 1)) +
      geom_col(aes(y=Bar*sfactor))+
      scale_y_continuous("Line",
                         sec.axis = sec_axis(trans= ~. /sfactor, name = "Bar"))
    

    输出:

    【讨论】:

    • 完美!另一个要求:如何标记条形?添加 > geom_text(aes(label=Bar)) 似乎不起作用。非常感谢
    • @wellokaythen 我建议您在每个几何图形之后添加标签,如下所示:geom_col(aes(y=Bar*sfactor))+geom_text(aes(y=Bar*sfactor,label=Bar))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 2019-10-27
    • 2017-06-05
    • 1970-01-01
    相关资源
    最近更新 更多