【问题标题】:Is there a way to add the percentage change label to the end of a graph有没有办法将百分比变化标签添加到图表的末尾
【发布时间】:2022-01-16 09:40:59
【问题描述】:

我创建了一个图表来演示四个变量的发展。有什么方法可以在图表的末尾添加一个标签来告诉百分比变化(最后一次观察/第一次观察-1)以突出观察期间的相对变化?

数据&绘图=

library(tidyverse)

Data <- data.frame(
  Wind = c(236,325,470,615,647,821),
  Hard_coal= c(591,811,667,681,532,344),
  Gas= c(883,841,472,731,678,680),
  Bio = c(883,841,811,731,678,680),
  year= c("2015","2016","2017","2018","2019","2020"))

Data %>% 
  pivot_longer(-year) %>% 
  ggplot(aes(x = year, y = value, color = name, group = name, linetype = name)) +
  geom_line(size = 1.5)

【问题讨论】:

  • (当然你需要先计算你的百分比变化,但我相信你能做到)
  • 我也对如何计算百分比变化并在这种特殊情况下应用感兴趣。因此,我投票重新提出这个问题。尽管提供的答案链接肯定涵盖了标签问题。计算和标注的结合不是。

标签: r ggplot2


【解决方案1】:

使用Plot labels at ends of lines 中提供的ggrepel 选项可以像这样实现,我使用dplyrs firstlast 来计算百分比变化。

注意:我仍然投票关闭这个问题作为重复。

library(tidyr)
library(dplyr)
library(ggplot2)

data_long <- Data %>% 
  pivot_longer(-year) %>%
  mutate(year = as.numeric(year)) %>% 
  group_by(name) %>% 
  mutate(change = last(value) / first(value) - 1)

ggplot(data_long, aes(x = year, y = value, color = name, group = name)) +
  geom_line(size = 1) +
  ggrepel::geom_text_repel(data = filter(data_long, year == max(year)), 
                           aes(label = scales::percent(change)), 
                           direction = "y", nudge_x = .25,
                           hjust = 0, show.legend = FALSE) +
  scale_x_continuous(limits = c(NA, 2020.5)) +
  coord_cartesian(clip = "off")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 2021-07-17
    • 2020-02-26
    • 2011-12-17
    • 2018-06-04
    相关资源
    最近更新 更多