如何强制y轴具有一组特定的构面值,其中GGPlot中的值为空

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

我有以下数据框:

library(tidyverse)

dat <-   structure(list(cluster = structure(c(1L, 1L, 1L, 1L, 10L, 10L, 
  10L, 10L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 
  5L, 5L, 5L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 9L, 
  9L, 9L, 9L), .Label = c("1", "2", "3", "4", "5", "6", "7", "8", 
  "9", "10"), class = "factor"), sample.category = structure(c(2L, 
  4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 
  4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 
  4L, 1L, 3L, 2L, 4L, 1L, 3L), .Label = c("YYY_All", "XXX_All", 
  "YYY_Foo+", "XXX_Foo+"), class = "factor"), n = c(0, 0, 
  0, 0, 0, 0, 80, 0, 0, 10, 0, 1, 0, 1, 0, 1, 0, 48, 1, 27, 0, 
  7, 0, 5, 0, 19, 1, 11, 0, 0, 0, 0, 0, 6, 31, 32, 0, 0, 2, 1)), row.names = c(NA, 
  -40L), class = c("tbl_df", "tbl", "data.frame"))


dat

使用此代码:

ggplot(dat, aes(x = sample.category, y = n)) +
  geom_col() +
  facet_wrap(~cluster, scales = "free") +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 60, hjust = 1, size = 10)) +
  ylab("") +
  xlab("")

我可以画出这个数字:

enter image description here

如该图所示,如何强制y轴具有一组值为空的构面值?

在这种情况下,y轴的值集是:c(0, 2.5, 5.0, 7.5, 10)

r ggplot2 tidyverse
1个回答
1
投票

您可以将一些虚拟数据与geom_blank()结合使用以获得预期的效果。

dummy <- data.frame(cluster = factor(c(1,7), levels = 1:10), 
                    sample.category = "XXX_all", n = 10)

ggplot(dat, aes(x = sample.category, y = n)) +
  geom_col() +
  geom_blank(data = dummy) +
  facet_wrap(~cluster, scales = "free") +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 60, hjust = 1, size = 10)) +
  ylab("") +
  xlab("")

enter image description here

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