对齐ggplot标签

时间:2018-10-09 14:04:52

标签: r ggplot2

我有一个数据集,可以在其中比较某些组(物种)中的一些新旧变化。我有一个图,可创建所需的输出,但标签不理想。我希望他们介于新旧酒吧之间。当标签的长度不同时,这有点棘手。

示例

library(ggplot2)
iris$change <- sample(c('new', 'old'), 150, replace = TRUE)
iris$mean1 <- ifelse(iris$Sepal.Length < mean(iris$Sepal.Length), 'Below', 'Above')

breaks

breaks <- unique(paste(iris$Species[iris$change == 'new'], iris$change[iris$change == 'new']))

ggplot(iris, aes(x = paste(Species, change), y = Petal.Width, fill = mean1)) +
  geom_bar(stat = 'identity', position = 'fill') +
  scale_x_discrete(breaks = breaks, labels = c('Setosa', 'vers', 'Virginica')) +
  theme(axis.text.x = element_text(hjust = -1.2)) + 
  geom_text(aes(label = ifelse(change == "new", 'new', '')), size = 3, y = 0.05) +
  geom_text(aes(label = ifelse(change == "old", 'old', '')), size = 3, y = 0.05)

1 个答案:

答案 0 :(得分:1)

我相信您可以使用多面切割来获得想要的东西:

library(ggplot2)
iris$change <- sample(c('new', 'old'), 150, replace = TRUE)
iris$mean1 <- ifelse(iris$Sepal.Length < mean(iris$Sepal.Length), 'Below', 'Above')

ggplot(iris, aes(x = change, y = Petal.Width, fill = mean1)) +
  geom_bar(stat = 'identity', position = 'fill') +
  facet_wrap(~Species, strip.position = "bottom")+
  theme(strip.placement = "outside", 
        strip.background = element_rect(colour = "white", fill = "white"))+
  xlab(NULL)