如何在ggplot中为条形图自定义主要网格线?

How to customise major grid line for bar chart in ggplot?

有人可以向我解释为什么以下代码无法更改 y 轴上的主要网格线吗?我希望它从 0 到 20,每 2 个单位有一条主线。该代码没有 return 任何错误。

Grade <- c(rep("6th" , 12) , rep("7th" , 13) , rep("8th" , 16) , rep("9th" , 9), 
           rep("10th" , 10) , rep("11th" , 6), rep("12th" , 3))
Gender <- c(rep("Male" , 5), rep("Female" , 7), rep("Nonbinary" , 0),
            rep("Male" , 5), rep("Female" , 8), rep("Nonbinary" , 0),
            rep("Male" , 7), rep("Female" , 8), rep("Nonbinary" , 1),
            rep("Male" , 4), rep("Female" , 4), rep("Nonbinary" , 1),
            rep("Male" , 6), rep("Female" , 4), rep("Nonbinary" , 0),
            rep("Male" , 2), rep("Female" , 4), rep("Nonbinary" , 0),
            rep("Male" , 0), rep("Female" , 3), rep("Nonbinary" , 0))
value <- rep("1", 69)
datas <- data.frame(Grade,Gender,value)
datas <- datas %>% arrange(desc(Grade)) %>% mutate(rank = c(rep("4" , 9) , rep("3" , 16) , 
                                 rep("2" , 13) , rep("1" , 12), 
                                 rep("7" , 3) , rep("6" , 6), 
                                 rep("5" , 10))) %>% arrange(desc(rank))
ggplot(datas, aes(x = rank, y = value, fill = Gender)) +
      geom_col(position = position_stack(reverse = TRUE)) + 
      scale_x_discrete(labels=c("1" = "6th", "2" = "7th","3" = "8th","4" = "9th", 
                                "5" = "10th", "6" = "11th", "7" = "12th")) + 
      scale_y_discrete(breaks = seq(0,20,2)) + 
      xlab('Grade') + ylab('')

.

您的问题是由于 value 是字符列而不是数字列。这使得 y 轴是分类的而不是数字的,因此您的中断将被忽略,因为在 y 轴上除了“1”之外没有其他类别可以放置中断。

因为值都是 1,您可以使用 geom_bar,这将使 y 轴成为计数。然后,您可以使用 scale_y_continuous 而不是 scale_y_discrete

添加中断
ggplot(datas, aes(x = rank, fill = Gender)) +
      geom_bar(position = position_stack(reverse = TRUE)) + 
      scale_x_discrete(labels=c("1" = "6th", "2" = "7th","3" = "8th","4" = "9th", 
                                "5" = "10th", "6" = "11th", "7" = "12th")) + 
      scale_y_continuous(breaks = seq(0,20,2)) + 
      xlab('Grade') + ylab('')

如果您想将 value 解释为数字(以防其中任何一个不是 1),则使用 geom_col,但将 value 转换为数字而不是字符:

ggplot(datas, aes(x = rank, y = as.numeric(value), fill = Gender)) +
      geom_col(position = position_stack(reverse = TRUE)) + 
      scale_x_discrete(labels=c("1" = "6th", "2" = "7th","3" = "8th","4" = "9th", 
                                "5" = "10th", "6" = "11th", "7" = "12th")) + 
      scale_y_continuous(breaks = seq(0,20,2)) + 
      xlab('Grade') + ylab('')