如何在 ggplot 中将连续的 x 轴更改为离散的 x 轴?

How to change a continuous x-axis into a discrete one in ggplot?

我有以下数据框:

df = structure(list(qCountry = c("AT", "DE", "ES", "FI", "FR", "GR", 
"HU", "IR", "IT", "LV", "NL", "POL", "PT", "RO", "SWE"), Mean = c(1.34199395770393, 
1.37664132688321, 1.29144095341278, 1.42088404868674, 1.45019920318725, 
1.29786200194363, 1.24528301886792, 1.26937046004843, 1.38345864661654, 
1.39706780696396, 1.38751714677641, 1.30804248861912, 1.28609062170706, 
1.2320819112628, 1.32588699080158), Sd = c(0.474520963779525, 
0.484711259139164, 0.454549282145671, 0.493859200850428, 0.497678958439859, 
0.45742966912063, 0.430377930416405, 0.443767080631815, 0.48638085640142, 
0.489439780963027, 0.487350499450418, 0.461801022550429, 0.452051373271304, 
0.422281105345888, 0.468859354590332)), class = c("tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -15L))

我想结合 geom_pointgeom_errorbar 绘制它。这不是问题。然而,x 轴是一个连续变量,而我希望 ggplot 只显示两个标签“是”和“否”对应于 1 和 2。我尝试了以下但它不起作用:


df %>% ggplot(aes(x = reorder(qCountry,-Mean), y = Mean, group = qCountry)) + geom_point(size = 3.5) +
  geom_errorbar(aes(ymin=Mean-Sd, ymax=Mean+Sd)) + labs(title = "Some Title",x = "", y="") + scale_y_discrete(labels= c("Yes", "No")) + coord_flip() + theme_classic2()


谁能帮帮我?

谢谢!

您不能有离散轴。但是你可以重新标记一个连续的轴,使 1 为“否”,2 为“是”

df %>% 
  ggplot(aes(x = reorder(qCountry,-Mean), y = Mean, group = qCountry)) + 
  geom_point(size = 3.5) +
  geom_errorbar(aes(ymin=Mean-Sd, ymax=Mean+Sd)) + 
  labs(title = "Some Title",x = "", y="") + 
  scale_y_continuous(breaks = c(1, 2), 
                     labels = c("No", "Yes"), limits = c(0.8, 2)) +
  coord_flip() + 
  theme_classic(base_size = 20)

请注意,您可能需要查看如何计算标准偏差,因为您的误差线延伸到 1 以下,这实际上没有意义。您可能想要计算二项式置信区间。