用ggplot将条形图的列与线图的点对齐 [英] Line up columns of bar graph with points of line plot with ggplot

查看:52
本文介绍了用ggplot将条形图的列与线图的点对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any way to line up the points of a line plot with the bars of a bar graph using ggplot when they have the same x-axis? Here is the sample data I'm trying to do it with.

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)

以下是输出:

折线图的第一个点在第一个小节的左侧,折线图的最后一个点在最后一个小节的右侧.

The first point of the line plot is to the left of the first bar, and the last point of the line plot is to the right of the last bar.

谢谢您的时间.

推荐答案

略微扩展@Stibu的帖子:要对齐图,请使用 gtable (或查看

Extending @Stibu's post a little: To align the plots, use gtable (Or see answers to 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

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

Edit To change heights of plots:

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)

这篇关于用ggplot将条形图的列与线图的点对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆