使用scale_x_continuous在ggplot2中复制离散x轴

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

我需要在 ggplot 上方和下方显示 x 轴的标签,与相应的数据点对齐。我已经创建了一个具有必要数据和美观的 ggplot,但我正在努力复制 x 轴,因为它是一个分类变量。

由于使用scale_x_discrete不可能复制轴,所以我尝试使用scale_x_continuous(),用中断分割分类变量并将字符向量定义为标签。 “plot”是我的带有数据和美学的 ggplot。 变量“birds$species_name”是包含鸟类物种名称的因子。

birds <- data.frame(species_name= c("eagle", "eagle", "robin", "vulture", "bee-eater"),
                 overall.percentage = c(12, 13, 19, 20, 12))

plot + scale_x_continuous(breaks = 1:length(unique(birds$species_name)),
                     labels = as.character(unique(birds$species_name)),
                     sec.axis = dup_axis())

根据之前在线问题的建议,我也尝试了这段代码。

plot + scale_x_continuous(breaks = 1:length(unique(birds$species_name)),
                          labels = as.character(unique(birds$species_name)),
                          sec_axis(~.,
                                   breaks = 1:length(unique(birds$species_name)),
                                   labels = as.character(unique(birds$species_name))))

我希望代码能够成功复制图中的 x 轴,但总是返回错误“提供给连续刻度的离散值”。

如有任何建议,我们将不胜感激,提前致谢!

r ggplot2 axis
1个回答
0
投票

这个想法是,您将离散轴转换为数字轴,自己提供标签,然后您可以轻松复制该轴:

library(ggplot2)

ggplot(iris, aes(x = as.integer(Species), y = Sepal.Width, color = Species)) +
  geom_point(position = position_jitter(height = 0)) + 
  scale_x_continuous("Species",
                     breaks = seq_len(nlevels(factor(iris$Species))),
                     labels = levels(factor(iris$Species)),
                     sec.axis = dup_axis()
                     )

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