[英]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()
即使您的目標是讓它看起來像是離散的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.