在 ggplot2 中自定义特定的 x 轴刻度

Customise specific x-axis ticks in ggplot2

听起来很容易,但我已经搜索了一段时间,但一无所获。

我有这个数据:

> df <- data.frame(themes = c("Restoration techniques", "Managing projects", "Ecology and hydrology", "Carbon benefits of peatland"), before = c(2.243243, 2.162162, 2.162162, 2.135135), after = c(2.366667, 2.366667, 2.366667, 2.233333))
> df
                       themes   before    after
2      Restoration techniques 2.243243 2.366667
1       Ecology and hydrology 2.162162 2.366667
4 Carbon benefits of peatland 2.162162 2.366667
3           Managing projects 2.135135 2.233333

我是这样设计的:

ggplot(df) +
  geom_segment(aes(x = fullname, xend = fullname, y = 1, yend = 3), color = "grey") +
  geom_segment(aes(x = fullname, xend = fullname, y = before, yend = after), color = "yellowgreen") +
  geom_point(aes(x = fullname, y = before), color = viridis(50)[40], size = 4) +
  geom_point(aes(x = fullname, y = after), color = viridis(50)[25], size = 4) +
  coord_flip() +
  theme_ipsum() +
  xlab("") + ylab("")

结果如下:

我想要的是更改水平轴上刻度的标签。

更具体地说,我不想要数字,我希望值 1 为“低”,值 2 为“中”,值 3 为“高”。

我尝试使用scale_x_discrete(),具体添加:

+
scale_x_discrete(breaks=c(1, 2, 3), labels=c("Low", "Medium", "High"))

但我得到的是下图:

我感觉问题可能出在 x 轴的性质上,但我不知道应该如何解决问题以及应该在绘图代码中添加哪几行。

您需要使用scale_y_continuous()如下:

ggplot(df) +
  geom_segment(aes(x = themes, xend = themes, y = 1, yend = 3), color = "grey") +
  geom_segment(aes(x = themes, xend = themes, y = before, yend = after), color = "yellowgreen") +
  geom_point(aes(x = themes, y = before), color = viridis(50)[40], size = 4) +
  geom_point(aes(x = themes, y = after), color = viridis(50)[25], size = 4) +
  coord_flip() +
  theme_ipsum() +
  xlab("") + ylab("") + 
  scale_y_continuous(breaks=c(1,2,3), labels=c("Low", "Medium", "High"))

您必须使用与您所拥有数据的性质相匹配的 scale_ 函数。由于您的 y 轴数据是连续的,因此您需要 scale_y_continuous(),即使您的目标是让它看起来像是离散的。