首页 > 解决方案 > 如何将单个标签添加到R中折线图上的点

问题描述

我想在显示平均温度变化的折线图上添加标签,指出 3 个最高温度和 3 个最低温度的年份。我无法弄清楚如何仅针对这 6 点而不是每一点来做到这一点......有什么帮助吗?

#load data up 
library(readxl)
TempData <- read_excel("R Data/TempData.xlsx")
View(TempData)

#initiliase relevant packages #ggplot2 for creating data visulation and viridis to allow for colour gradients
library(ggplot2)
library(viridis)

#plot line graph
g1 <- ggplot(TempData, aes(x = Year, y = GAT, color = GAT)) +
  geom_line(size = 1.5)  +
  geom_smooth(method=loess, se=TRUE, col = "black") +
  scale_colour_gradient2(low = "green", mid = "yellow" , high = "red", midpoint=median(TempData$GAT)) +
  labs(title = "Global Average Temperature", subtitle = "From 1850 to 2018") +
  xlab("Year") +  ylab ("Average Temperature") +
  theme(plot.title = element_text(face = "bold", hjust = 0.5, size = 16)) +
  theme(plot.subtitle = element_text(face = "italic", hjust = 0.5, size = 10, colour = "Orange")) +
  theme_light()

plot(g1)

标签: rggplot2

解决方案


正如@Nate 建议的那样,一种常见的方法是将数据的子集输入geom_text. 您可以在之前定义那些,ggplot2或者如果它很简单,定义那些内联并输入该层自己的data术语。在这里,我dplyr::top_n用来抓取前 3 名和后 3 名的权重。

library(dplyr)
ggplot(mtcars, aes(x = wt, y = mpg, color = hp, label = mpg)) +
  geom_line(size = 1.5)  +
  geom_smooth(method=loess, se=TRUE, col = "black") +
  scale_colour_gradient2(low = "green", mid = "yellow" , high = "red", 
                         midpoint=median(mtcars$hp))  +
  geom_text(data = mtcars %>% top_n(3, wt), 
            hjust = 1.5, color = "black", angle = 90) +
  geom_text(data = mtcars %>% top_n(-3, wt), 
            hjust = -0.5, color = "black", angle = 90) +
  theme_light()

我们没有您的数据,所以我将您的代码应用到标准mtcars数据集。(不是一个很好的审美匹配,但你明白了......)

在此处输入图像描述


推荐阅读