【问题标题】:R ggplot annotate line plot with max valueR ggplot用最大值注释线图
【发布时间】:2021-05-12 16:01:15
【问题描述】:

我有一个使用此代码创建的线图:

# Create data
year <- c(2006,2007,2008,2009,2010,2011,2012,2013,2014)
sales <- c(4176,8560,6473,10465,14977,15421,14805,11183,10012)
df <- data.frame(year,sales)

# Plot
ggplot(data = df,aes(year, sales),group = 1) + geom_point() + geom_line()

我想用“显示”最大值的行来注释它,如下例所示:

ggplot 可以做到这一点吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    是的。对于您当前的示例,请尝试以下操作:

    ggplot(data = df,aes(year, sales),group = 1) + geom_point() + geom_line() + 
           geom_segment(aes(x = 2011, y = 0, xend = 2011, yend = 15421),linetype="dashed", color = "red")
    

    当然,对于更一般的绘图需求,您可以改进代码而不是在这里手动输入值。

    【讨论】:

      【解决方案2】:

      这很接近,只需要箭头:

      ggplot(data = df,aes(year, sales),group = 1) + geom_point() + geom_line() + theme_bw() + 
        geom_linerange(aes(ymax=sales, ymin=min(df$sales)), 
                       data=df[which.max(df$sales),], 
                       col="red", lty=2) + 
        geom_text(aes(label=sales),data=df[which.max(df$sales),], hjust=1.2, vjust=3)
      

      它通过添加 geom_linerangegeom_text geoms 来工作,但将每个的数据设置为原始数据集对应于“销售”列的最大值的行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-21
        • 1970-01-01
        • 2017-03-27
        • 1970-01-01
        • 2020-03-09
        • 2017-11-27
        • 1970-01-01
        • 2020-02-23
        相关资源
        最近更新 更多