如何解决在 ggplot2 中自定义特定的 x 轴刻度
听起来很简单,但我一直在寻找,但一无所获。
我有这个数据:
> df <- data.frame(themes = c("Restoration techniques","Managing projects","Ecology and hydrology","Carbon benefits of peatland"),before = c(2.243243,2.162162,2.135135),after = c(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,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(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,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()
,即使您的目标是让它看起来好像是离散的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。