在R中的ggplot中保持宽度恒定

时间:2018-12-11 07:04:32

标签: r ggplot2

已经尝试过此link,但是它没有用,而且这个问题是5年前提出的,所以我希望有比这种冗长的代码更好的方法。

如何使用ggplot使多个条形图的条形和它们之间的间距固定,而每个图上的条形数量不同?

#with 10 bins
data <- data.frame(x=1:10,y=runif(10))
library(ggplot2)
ggplot(data, aes(x,y)) + geom_bar(stat="identity")

#with 3 bins
ggplot(data[1:3,], aes(x,y)) + geom_bar(stat="identity")

向geom_bar(...)添加width = 1也无济于事。我需要自动绘制第二个图,以使其宽度小于第一个图,并具有与第一个图相同的条宽度和空格。

1 个答案:

答案 0 :(得分:1)

一种解决方案是调整坐标以匹配:

ggplot(data[1:3,], aes(x,y)) + geom_bar(stat="identity") +
scale_x_continuous(limits = c(0.5,10)) # This is approximate but pretty close.
#
# For an exact match, you can go into the ggplot_build object and
# extract [["layout"]][["panel_params"]][[1]][["x.range"]]
# You could then use the exact values:
# scale_x_continuous(limits = c(0.055,10.945), expand = c(0,0))

enter image description here

另一种方法是将条形图合并为一个图,然后使用构面以相同的比例显示数据。

library(dplyr)
data2 <- 
  data %>% mutate(plot = "A") %>%
  bind_rows(
    data[1:3,] %>% mutate(plot = "B")
  )

(a <- ggplot(data2, aes(x,y)) + geom_bar(stat="identity") +
  facet_grid(~plot)
)

如果要与plotly一起使用,则可以使用plotly::ggplotly(a)。  enter image description here