我使用 ggplot 在图表上绘制了 2 条线,特别是使用“选择”和“收集”工具,使用此方法将两条线变量折叠为键值对(此处的解决方案 2):https://www .datanovia.com/en/blog/how-to-create-a-ggplot-with-multiple-lines/
一切正常,除了我无法弄清楚如何使用“Desc”变量来标记一条线的点。以下代码使用 Desc 变量标记这两行,但我只想标记“海拔”行。有什么想法吗?
#preparing data
library("tidyverse")
df <- mydatacsv %>%
select(Meter, Stem_Height,Elevation,Desc) %>%
gather(key = "Legend", value = "value", -Meter,-Desc)
head(df,n=200)
# Visualization
ggplot(df, aes(x = Meter, y = value,label=Desc)) +
geom_line(aes(color = Legend)) +
scale_color_manual(values = c("green4","black")) +
geom_point(data=mydatacsv, aes(y = Stem_Height),color="green4")+
geom_point(data=mydatacsv, aes(y = Elevation),color="black")+
xlab("Distance (m)") +
ylab("Elevation (m)")+
geom_text_repel(max.overlaps=Inf,hjust=-0.1, angle=90)
我想要绘制两条线,仅绘制一条线的绘图点标签。相反,它在图表上放置双标签,每条线上的每个绘图点都有一个标签。
您只能通过至少三种方式标记所需的组。
使用示例数据
mtcars
并针对每个 hp
级别绘制 mpg
与 gear
,但仅标记具有三个档位的汽车的观察结果:
mtcars |>
ggplot() +
geom_text(aes(hp, mpg, label = ifelse(gear == 3, mpg, NA)))
mtcars |>
ggplot() +
geom_text(data = mtcars |> filter(gear == 3),
aes(hp, mpg, label = mpg)
)
alpha
(不透明度)设置为零:mtcars |>
ggplot() +
geom_text(aes(hp, mpg, label = mpg, alpha = gear == 3)) +
scale_alpha_identity()
由于您使用的是
tidyverse
软件包,请将您不想要的标签更改为 NA
或空白 ""
。两者中的任何一个都会删除一行标签,NA
会发出警告。suppressPackageStartupMessages({
library(dplyr)
library(ggplot2)
library(ggrepel)
})
# reproducible test data
set.seed(2023)
df1 <- replicate(2, cumsum(rnorm(20))) |> as.data.frame()
df1$Legend <- rep(c("A", "B"), each = 10L)
df1$Desc <- with(df1, ave(V1, Legend, FUN = \(x) paste("text", seq_along(x))))
names(df1)[1:2] <- c("Meter", "value")
head(df1)
#> Meter value Legend Desc
#> 1 -0.08378436 -0.4116530 A text 1
#> 2 -1.06672810 -0.7059802 A text 2
#> 3 -2.94179542 0.5125938 A text 3
#> 4 -3.12794008 0.7567052 A text 4
#> 5 -3.76142578 0.3115533 A text 5
#> 6 -2.67062832 -1.5362504 A text 6
df1 %>%
# mutate(Desc = ifelse(Legend == "A", Desc, NA_character_)) %>%
mutate(Desc = ifelse(Legend == "A", Desc, "")) %>%
ggplot(aes(Meter, value, color = Legend, label = Desc)) +
geom_line() +
geom_point() +
geom_text_repel(max.overlaps=Inf,hjust=-0.1, angle=90) +
scale_color_manual(values = c("green4", "black")) +
xlab("Distance (m)") +
ylab("Elevation (m)") +
theme_bw()
创建于 2023-08-14,使用 reprex v2.0.2