使用 ggplot2 向 y 轴添加不带刻度线的附加标签

问题描述 投票:0回答:1

类似于这个问题how to add a text label in the y-axis in ggplot2,缺乏示例和令人满意的答案,我想知道是否有任何方法可以在轴上放置额外的标签,大多数时候这可能是 y 轴。附加标签应出现在指定位置。应该可以独立于“正常”刻度标签来设置附加标签的样式。并且:它应该没有勾号(而“正常”勾号标签可能/应该有勾号)。

一个例子:

# Sample dataframe
df <- data.frame(
  x = c(1, 2.6, 3, 4, 5),
  y = c(2, 5, 3.6, 8.2, 10),
  y_ticks = c(2, 4, 5, 8, 10),
  y_labels = c("Low", "Mid-Low", "Medium", "Mid-High", "High")
)

# Create a scatter plot with custom y-axis ticks and labels
library (ggplot2)
ggplot(df, aes(x, y)) +
  geom_point() +
  scale_y_continuous(breaks = df$y_ticks, labels = df$y_labels) 

这给出了:

我想要的是在 y = 6 处添加一个不带刻度线的标签(可以说“较低值”)。 我试着用手把它画成红色来展示目的:

我已经尝试过不同的事情,但我无法弄清楚。也许有人可以帮忙?

r ggplot2 axis-labels
1个回答
0
投票
# Sample dataframe
df <- data.frame(
  x = c(1, 2.6, 3, 4, 5),
  y = c(2, 5, 3.6, 8.2, 10),
  y_ticks = c(2, 4, 5, 8, 10),
  y_labels = c("Low", "Mid-Low", "Medium", "Mid-High", "High")
)

# Create a scatter plot with custom y-axis ticks and labels
library (ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.3.2

ylabs_new <- 
  data.frame(y_ticks = c(2, 4, 5, 5.5, 8, 10),
             y_labels = c("Low", "Mid-Low", "Medium", "Lower", "Mid-High", "High"),
             size = c(rep(1, 3), 0, rep(1, 2)),
             text = c(rep(10, 3), 14, rep(10, 2)))




ggplot(df, aes(x, y)) +
  geom_point() +
  scale_y_continuous(breaks = ylabs_new$y_ticks, 
                     labels = ylabs_new$y_labels) +
  theme(axis.ticks.y = element_line(size = ylabs_new$size),
        axis.text.y = element_text(size = ylabs_new$text))
#> Warning: Vectorized input to `element_text()` is not officially supported.
#> ℹ Results may be unexpected or may change in future versions of ggplot2.
#> Warning: The `size` argument of `element_line()` is deprecated as of ggplot2 3.4.0.
#> ℹ Please use the `linewidth` argument instead.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.

创建于 2023 年 11 月 29 日,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.