【问题标题】:How to remove extra column in facet_wrap plot with ggplot2?如何使用 ggplot2 删除 facet_wrap 图中的额外列?
【发布时间】:2021-10-01 03:45:46
【问题描述】:

我正在尝试使用带有不平衡分组数据的facet_wrap 生成分面图,它提供了一个带有额外空白轴列的图。

如段落所示,我想生成一个没有最右边轴列的图。

这是一个示例代码:

library(ggplot2)
name <- c(factor(letters[1:4]),factor(LETTERS[1:3]))
room <- rep(c('A','B'),c(4,3))
goal <- c(rnorm(7,mean=60,sd=10))
test <- data.frame(name,goal,room) 
test %>% ggplot(aes(name, goal))+
  facet_wrap(~factor(room))+
  geom_bar(stat = "identity")

'scales="free"' 方式:自动设置,可以手动设置吗?

@teunbrand 开发的ggh4x 中的facetted_pos_scales 解决了这个问题,谢谢!这是补充代码:

library(ggh4x)

scales <- list(
  scale_y_continuous(limits = c(0, 100)),
  scale_y_continuous(limits = c(0, 80))
)

test %>% ggplot(aes(name, goal))+
  facet_wrap(~factor(room), scales="free")+
  geom_bar(stat = "identity")+
  facetted_pos_scales(y=scales)

【问题讨论】:

  • facet_wrap 中使用scales = 'free_x',即facet_wrap(~factor(room), scales = 'free_x')
  • 谢谢!它运作良好。还有一个问题,如何在右侧子图中添加 y 轴并最小化它们之间的间隙?
  • 您可以从可以使用scale_y_continuous(limits = function(x){do_something_here}) 的预先存在的限制中得出所需的限制。否则,您可能会求助于a bit of a hack(免责声明:我编写了链接函数)。
  • @teunbrand ,真是一个hack包,正是我需要的!这是代码` library(ggh4x) scales % ggplot(aes(name, goal) )+ facet_wrap(~factor(room), scales="free")+ geom_bar(stat = "identity")+ facetted_pos_scales(y=scales) `

标签: r ggplot2 facet-wrap


【解决方案1】:

关于 op 评论的更新: 这有帮助吗:您可以使用coord_cartesian(ylim = c(0, 90)) 设置ylim:

test %>% ggplot(aes(name, goal))+
  geom_bar(stat = "identity")+
  coord_cartesian(ylim = c(0, 100)) +
  facet_wrap(~factor(room), scales="free")

使用scales="free" 而不是scales="free_x"

library(ggplot2)
name <- c(factor(letters[1:4]),factor(LETTERS[1:3]))
room <- rep(c('A','B'),c(4,3))
goal <- c(rnorm(7,mean=60,sd=10))
test <- data.frame(name,goal,room) 
test %>% ggplot(aes(name, goal))+
  facet_wrap(~factor(room), scales="free")+
  geom_bar(stat = "identity")

【讨论】:

  • 谢谢!但它产生了另一个问题,两个子图没有共享相同的轴长度或如何自定义子图轴标签?两个轴的长度都是 100,或者左图是 100,右图是 80,依此类推。
  • 可以设置scale_y_continuous(limits = your_limits_here)
  • @teunbrand ,我知道,但它不能像我希望的那样为两个图自定义不同的轴。例如:左图为 100,右图为 80,依此类推。
  • 我不确定。但请参阅我的编辑。使用 coord_cartesian(ylim = c(0, 100)) 单独设置 ylim
  • @TarJae,和facetted_pos_scales有类似的功能,问题解决了!
猜你喜欢
  • 2012-07-27
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-13
  • 2013-07-30
相关资源
最近更新 更多