5

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!

1
  • 2
    This is pretty easy by reshaping (reshape2::melt) and then using an aesthetic such as colour (or simply group) to distinguish the two variables. You need to melt in such a way that you keep often_privacy as an id variable. If you post a small subset of your data (with dput) I'm sure you'll get an answer. Commented Jun 28, 2012 at 11:28

3 Answers 3

10

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()
)
Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

this answers the question nicely, although I think my comment above suggests the more 'idiomatic' way to do it (which among other things provides (1) an automatic legend (2) more compact code [although for only two variables there's not a big advantage])
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.