-2

My codes are:

ggplot(data=df2, aes(x=stress, fill=as.factor(JP_Gender))) + geom_density(alpha=.3)
ggplot(data=df1, aes(x=CGstress)) + geom_density(alpha=.3)

My dataset 1:

structure(list(CGstress = c(4, 1, 10, 8, 9.5, 5, 5, 6, 6, 6, 
7, 3, 4.5, 8, 9, 1, 5, 1, 5.5, 4, 1, 7, 9, 8, 3, NA, 10, 9, 5, 
3, NA, 10, 6, NA, 10, 7)), row.names = c(NA, -36L), class = c("tbl_df", 
"tbl", "data.frame"))

My dataset 2:

structure(list(stress = c(7, 2, 5, 6, 7, 1, 6, 10, 9, 10, 10, 
10, 10, 8, 9, 4, 7, 6, 4, 9, 4, 8, 3.5, 7, 6, 6, 1, 7, 9, 8, 
10, 6, 3, 1, 1, 1, 9, 6, 4), JP_Gender = structure(c(1, 2, 1, 
2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
2, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1), label = "What is your gender?", format.stata = "%12.0g", labels = c(Male = 1, 
Female = 2, Transgender = 3, Other = 4), class = c("haven_labelled", 
"vctrs_vctr", "double"))), row.names = c(NA, -39L), class = c("tbl_df", 
"tbl", "data.frame"))

Above codes give me 2 graphs. How to combine 2 graphs into one plot? And how to label the legends?

1st graph 2nd graph

Chiao
  • 13
  • 2
  • Have you tried solutions from here https://stackoverflow.com/questions/1249548/side-by-side-plots-with-ggplot2 ? It would be easier to help if you create a small reproducible example. Read about [how to give a reproducible example](http://stackoverflow.com/questions/5963269). – Ronak Shah Feb 12 '21 at 02:57
  • @RonakShah that solution is not what I want. I don't wanna side-by-side. I want to draw three curves into one plot. – Chiao Feb 14 '21 at 05:36

1 Answers1

0

You can try combining the two datasets and then plot :

library(dplyr)
library(ggplot2)

df1 %>%
  mutate(id = 3) %>%
  rename(stress = CGstress) %>%
  bind_rows(df2 %>%
  mutate(id = as.integer(JP_Gender)) %>%
  select(stress, id)) %>%
  mutate(id = factor(id)) %>%
  ggplot(aes(x=stress, fill=factor(id))) + geom_density(alpha=.3)

enter image description here

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213