Computing two variables using ggplot2 - same x axis

I have two graphs with the same x axis - the x range is 0-5 in both of them. I would like to combine both of them into one graph, and I did not find the previous example. Here is what I got:

c <- ggplot(survey, aes(often_post,often_privacy)) + stat_smooth(method="loess")
c <- ggplot(survey, aes(frequent_read,often_privacy)) + stat_smooth(method="loess")

How can I combine them? The y axis is often confidential, and on each chart, the x axis is often published or read frequently. I thought that I can easily combine them (one way or another), because both of them have 0-5.

Many thanks!

+5
source share
3 answers

You can use +to combine other charts into one and the same object ggplot. For example, to plot points and smooth lines for both pairs of columns:

ggplot(survey, aes(often_post,often_privacy)) + 
geom_point() +
geom_smooth() + 
geom_point(aes(frequent_read,often_privacy)) + 
geom_smooth(aes(frequent_read,often_privacy))
+4

Ben.

#Sample data
survey <- data.frame(
  often_post = runif(10, 0, 5), 
  frequent_read = 5 * rbeta(10, 1, 1), 
  often_privacy = sample(10, replace = TRUE)
)
#Reshape the data frame
survey2 <- melt(survey, measure.vars = c("often_post", "frequent_read"))
#Plot using colour as an aesthetic to distinguish lines
(p <- ggplot(survey2, aes(value, often_privacy, colour = variable)) + 
  geom_point() +
  geom_smooth()
)
+10

:

df <- data.frame(x=x_var, y=y1_var, type='y1') 
df <- rbind(df, data.frame(x=x_var, y=y2_var, type='y2'))
ggplot(df, aes(x, y, group=type, col=type)) + geom_line()

enter image description here

0
source

All Articles