Align columns of a bar graph with dots on a line graph using ggplot

Is there a way to plot the points of a line graph using histogram columns using ggplot when they have the same x axis? Here is an example of the data I'm trying to do this.

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)

Here is the result:

enter image description here

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

Thank you for your time.

+4
source share
2 answers

The @Stibu extension is a bit: to align the graphs, use gtable(or see the answers to your previous 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

enter image description here

Edit To change the height of the graphs:

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)
+1
source

( ) x :

  • , 0,5 27,5, 1 27. , , - . axex , x. ,

    yes <- yes + scale_x_continuous(limits=c(0,28))
    no <- no + scale_x_continuous(limits=c(0,28))
    grid.arrange(no, yes)
    

    limits x. , , . y , . : enter image description here

  • , , x ggplot , . , . -,

    all <- rbind(data.frame(other_data,type="other"),data.frame(data,type="data"))
    

    :

    ggplot(all,aes(x=x,y=y)) + facet_grid(type~.,scales = "free_y") +
       geom_bar(data=subset(all,type=="other"),stat="identity") +
       geom_point(data=subset(all,type=="data")) +
       geom_line(data=subset(all,type=="data"))
    

    , type, . geom , geom. facet_grid scales = "free_y", y . :

enter image description here

, all. , :

+ theme(strip.background = element_blank(), strip.text = element_blank())
+1

All Articles