【问题标题】:Set axis for multiple plots in ggplot在ggplot中为多个图设置轴
【发布时间】:2016-08-01 06:31:10
【问题描述】:

我正在制作一个应该保存为 gif 的人口金字塔。 Kind of like in this tutorial of Flowing Data,但使用 ggplot 而不是 plotrix

我的工作流程:

1) 创建人口金字塔

2) 在for-loop 中创建多个金字塔图

for (i in unique(d$jahr)) {

  d_jahr <- d %>%
    filter(jahr == i)

  p <- ggplot(data = d_jahr, aes(x = anzahl, y = value, fill = art)) +
    geom_bar(data = filter(d_jahr, art == "w"), stat = "identity") +
    geom_bar(data = filter(d_jahr, art == "m"), stat = "identity") +
    coord_flip() +
    labs(title = paste(i), x = NULL, y = NULL)

  ggsave(p,filename=paste("img/",i,".png",sep=""))

}

3) 使用 animation 包将绘图保存为 gif

我的问题:

所有年份都有不同的值,因此 x 轴有不同的范围。这会导致 gif 中出现奇怪的外观,因为图的中心会向右、向左、向右跳跃……

是否可以在独立创建的多个绘图上固定 x 轴(在本例中为 y 轴,因为 coord-flip())?

【问题讨论】:

标签: r plot ggplot2 gif


【解决方案1】:

您可以通过设置limits参数来固定轴的范围:

library(ggplot2)
lst <- list(
  data.frame(x = 1:100, y=runif(100, 0, 10)),
  data.frame(x = 1:100, y=runif(100, 0, 100))
)
ylim <- range(do.call(c, lapply(lst, "[[", "y")))
for (x in seq(lst)) {
  print(ggplot(lst[[x]], aes(x, y)) + geom_point() + scale_y_continuous(limits=ylim))
}

或添加+ylim(ylim) 而不是+scale_y_continuous(limits=ylim)(通过@DeveauP)。

【讨论】:

  • 如果是设置限制,xlimylim函数可能比scale_y_continuous更合适。
  • 对,补充说。谢谢!
猜你喜欢
  • 2011-11-25
  • 2022-01-12
  • 1970-01-01
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多