我需要在ggplot上方和下方显示x轴的标签,并与相应的数据点对齐.我已经用必要的数据和美学创建了一个ggplot,但我很难复制x轴,因为它是一个分类变量.
由于scale_x_discrete不可能复制轴,因此我try 使用scale_x_continuous(),用断点拆分类别变量,并将字符载体定义为标签. "plot"是我的数据和美学ggplot. 变量"birds$species_list"是一个包含鸟类物种名称的因子,按百分比值增加排序.
library(ggplot2)
library(data.table)
birds <- data.frame(species_name= c("eagle", "eagle", "robin", "vulture", "bee-eater"),
overall.percentage = c(12, 33, 19, 20, 15))
# reorder the species according to their lowest percentage value
x <- setDT(birds)[,.(.(sort(overall.percentage))), species_name]
birds[
setorder(setDT(transpose(x[[2]]))[,species_name := x[[1]]])[,order := .I],
on = "species_name", order := order]
plot<-
ggplot(birds, aes(x=reorder(species_name, order), overall.percentage)) +
geom_point(position = position_jitter(w = 0.25, h = 0))
plot + scale_x_continuous(breaks = 1:length(unique(birds$species_name)),
labels = as.character(unique(birds$species_name)),
sec.axis = dup_axis())
正如之前网上问题所建议的那样,我也try 了这个代码.
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轴,但总是向我返回错误"将离散值提供给连续比例". 这可能是与订购操作相关的问题吗?
任何建议都将不胜感激,提前感谢!