【问题标题】:How to plot only Global Maximum Value using geom_text?如何使用 geom_text 仅绘制全局最大值?
【发布时间】:2020-03-27 20:12:24
【问题描述】:
df%>%
  group_by(approved_date)%>%
  summarise(rev=sum(gmv))%>%
  ggplot(aes(x = approved_date, y = rev)) + 
    geom_line() + 
    geom_smooth(method = 'auto', se = FALSE) + 
    labs(x = 'Date', y = 'Revenue', title = 'Revenue by Date') +
    scale_y_continuous(labels = function(x) format(x, scientific = FALSE)) +
    stat_peaks(colour = "red", span = NULL) + 
    stat_valleys(colour = "blue", span = NULL) + 
    geom_text(aes(label = round(rev, 0)),
              vjust = "inward", 
              hjust = "inward",
              show.legend = FALSE,
              check_overlap = TRUE)

我有这段代码,它在运行时标记了 Local Maxima 和 Minima 的所有值。我只想要全局最大值和全局最小值的值。如何做到这一点?

【问题讨论】:

  • 请展示一个可重现的小例子

标签: r ggplot2 geom-text ggpmisc


【解决方案1】:

由于缺少数据,问题中的代码无法运行,我展示了一个从包用户指南稍作修改的示例。在这种情况下,这个不同的例子应该足以解决问题。

library(ggpmisc)
ggplot(lynx, as.numeric = FALSE) + geom_line() + 
  stat_peaks(colour = "red") +
  stat_peaks(geom = "text", colour = "red", vjust = -0.5, 
             check_overlap = TRUE, span = NULL) +
  ylim(-100, 7300)

换句话说,geom "text" 应该作为参数传递给 stat_peaks() 以及 span = NULL 以获得单个标签。如果您直接添加geom_text(),则不会选择峰值,而是将存储在映射到label 美学的变量中的所有值添加到绘图中。

【讨论】:

  • 我在上面使用了一个不同的示例,以便我可以验证我的答案中的代码是否确实有效。一般来说,最好在问题中包含演示问题但可以运行的最简单示例,这通常意味着使您自己的小型数据集可用或使用 R 中包含的数据或代码中的包。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-25
  • 2021-09-01
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多