Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting two variables using ggplot2 - same x axis

Tags:

plot

r

ggplot2

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!

like image 608
Oshrat Avatar asked Jun 28 '12 10:06

Oshrat


2 Answers

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))
like image 38
Mathew Hall Avatar answered Nov 03 '22 01:11

Mathew Hall


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()
)
like image 91
Richie Cotton Avatar answered Nov 03 '22 00:11

Richie Cotton