当它们具有相同的x轴时,是否可以使用ggplot将线形图的点与条形图的线对齐?这是我尝试使用的示例数据。

library(ggplot2)
library(gridExtra)

data=data.frame(x=rep(1:27, each=5), y = rep(1:5, times = 27))
yes <- ggplot(data, aes(x = x, y = y))
yes <- yes + geom_point() + geom_line()

other_data = data.frame(x = 1:27, y = 50:76  )

no <- ggplot(other_data, aes(x=x, y=y))
no <- no + geom_bar(stat = "identity")

grid.arrange(no, yes)


这是输出:



折线图的第一个点在第一个条形图的左侧,而折线图的最后一个点在最后一个条形图的右侧。

感谢您的时间。

最佳答案

稍微扩展@Stibu的帖子:要对齐图,请使用gtable(或查看your earlier question的答案)

library(ggplot2)
library(gtable)

data=data.frame(x=rep(1:27, each=5), y = rep(1:5, times = 27))
yes <- ggplot(data, aes(x = x, y = y))
yes <- yes + geom_point() + geom_line() +
   scale_x_continuous(limits = c(0,28), expand = c(0,0))

other_data = data.frame(x = 1:27, y = 50:76  )

no <- ggplot(other_data, aes(x=x, y=y))
no <- no + geom_bar(stat = "identity") +
   scale_x_continuous(limits = c(0,28), expand = c(0,0))

gYes = ggplotGrob(yes)   # get the ggplot grobs
gNo = ggplotGrob(no)

plot(rbind(gNo, gYes, size = "first"))   # Arrange and plot the grobs




编辑要更改地块的高度,请执行以下操作:

g = rbind(gNo, gYes, size = "first")  # Combine the plots
panels <- g$layout$t[grepl("panel", g$layout$name)] # Get the positions for plot panels
g$heights[panels] <- unit(c(0.7, 0.3), "null") # Replace heights with your relative heights
plot(g)

关于r - 用ggplot将条形图的列与线图的点对齐,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30425900/

10-12 20:34