R语言 ggplot:将轴设置为一定范围

bgibtngc  于 2023-03-20  发布在  其他
关注(0)|答案(2)|浏览(268)

我正在拼命地尝试将刻度范围设置为1到5。我尝试使用ylim()scale_y_continuous(breaks = seq(1,5,1))coord_cartesian(ylim=c(1,5))。如何才能做到这一点?谢谢帮助!

n <- 10000

test <- data.frame(value = sample(1:5, size = n, replace = TRUE),
                   grp = sample(c("A", "B", "C"), size = n, replace = TRUE),
                   item = sample(c("Item1", "Item2", "Item3", "Item4", "Item5", "Item6"), size = n, replace = TRUE)) 
                   
test %>%
  group_by(item, grp) %>%
  summarise(mean = mean(value, na.rm=TRUE)) %>%
  ungroup() %>%
  
  ggplot(aes(x = item, y = mean, group = grp, fill = grp)) +
    geom_col(position = 'dodge') +
    coord_cartesian(ylim=c(1, 5)) +
    coord_flip()
sr4lhrrt

sr4lhrrt1#

您 * 可以 * 将ylim放入coord_flip

test %>%
  group_by(item, grp) %>%
  summarise(mean = mean(value, na.rm=TRUE)) %>%
  ungroup() %>%
  ggplot(aes(x = item, y = mean, group = grp, fill = grp)) +
  geom_col(position = 'dodge') +
  coord_flip(ylim = c(1, 5))

更妙的是,* 不要 * 使用coord_flipgeom_col的默认行为是,如果你有一个分类的y轴和一个数字的x轴,那么它会使条形图水平。我总是发现coord_flip在应用刻度和主题时会让人困惑,所以你可以把item放在y轴上,mean放在x轴上,并坚持在coord_cartesian中使用xlim

test %>%
  group_by(item, grp) %>%
  summarise(mean = mean(value, na.rm=TRUE)) %>%
  ungroup() %>%
  ggplot(aes(x = mean, y = item, fill = grp)) +
  geom_col(position = 'dodge') +
  coord_cartesian(xlim = c(1, 5))

更好的方法是在geom_bar中使用stat = "summary",这样就根本不需要总结 Dataframe :

ggplot(test, aes(x = value, y = item, fill = grp)) +
  geom_bar(stat = 'summary', position = 'dodge') +
  coord_cartesian(xlim = c(1, 5))

2exbekwf

2exbekwf2#

您可以像这样在scale_x_continuous中使用limits

n <- 10000

test <- data.frame(value = sample(1:5, size = n, replace = TRUE),
                   grp = sample(c("A", "B", "C"), size = n, replace = TRUE),
                   item = sample(c("Item1", "Item2", "Item3", "Item4", "Item5", "Item6"), size = n, replace = TRUE)) 
library(tidyverse)
test %>%
  group_by(item, grp) %>%
  summarise(mean = mean(value, na.rm=TRUE)) %>%
  ungroup() %>%
  ggplot(aes(x = item, y = mean, group = grp, fill = grp)) +
  geom_col(position = 'dodge') +
  scale_y_continuous(breaks = seq(1,5,1), limits = c(0, 5)) +
  coord_flip()

创建于2023年3月16日,使用reprex v2.0.2

相关问题