Oshrat
Oshrat

Reputation: 195

Plotting two variables using ggplot2 - same x axis

I have two graphs with the same x axis - the range of x is 0-5 in both of them. I would like to combine both of them to one graph and I didn't find a 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 privacy" and in each graph the x axis is "often post" or "frequent read". I thought I can combine them easily (somehow) because the range is 0-5 in both of them.

Many thanks!

Upvotes: 5

Views: 18272

Answers (3)

Sandipan Dey
Sandipan Dey

Reputation: 23101

Try this:

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

Upvotes: 0

Richie Cotton
Richie Cotton

Reputation: 121057

Example code for Ben's solution.

#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()
)

Upvotes: 10

Mathew Hall
Mathew Hall

Reputation: 1004

You can use + to combine other plots on the same ggplot object. For example, to plot points and smoothed 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))

Upvotes: 4

Related Questions