r - 如何将单个标签添加到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)
解决方案
正如@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
数据集。(不是一个很好的审美匹配,但你明白了......)
推荐阅读
- python - 给定一个对象列表,希望该对象返回它存储到的列表对象
- python - How to sum up pandas columns where the number is determined by the values of another column?
- c++ - Two methods with the same name but in different classes c++
- scala - How to combine 2 future sequences of type Seq[Either[A,B]]?
- r - 我怎样才能建立这个方程来进行约束最大化?
- node.js - 来自 ReactJS 的 Socket.io 连接没有像其他任何一样被 nginx 重定向
- python - Python - 在没有计数功能的列表中出现一个字符
- python - sklearn出现错误(LogisticRegression模型选择)
- java - 将 VBox 和 StackPane 放入另一个 StackPane 后,按钮不起作用
- c++ - XSLXWriter 在列的单元格中心插入多个图像