0

I have data of the following form.

v1   v2
t1    2.2
t1    3.2
t1    2.2
t1    2.2
t1    4.0
t2    3.8
t2    2.0
t2    2.1
t2    2.0
t2    3.0

I want the histogram of v2 for the categories of v1 on the same plot (using density). Can one help me, please?

iGada
  • 599
  • 3
  • 9

2 Answers2

2

You can try a facet approach using ggplot2 with facet_wrap(). We will use geom_density() to obtain the densities. Here the code:

library(ggplot2)
library(dplyr)

Data

#Data
df <- structure(list(v1 = c("t1", "t1", "t1", "t1", "t1", "t2", "t2", 
"t2", "t2", "t2"), v2 = c(2.2, 3.2, 2.2, 2.2, 4, 3.8, 2, 2.1, 
2, 3)), class = "data.frame", row.names = c(NA, -10L))

Code

#Code for plot
df %>%
  ggplot(aes(x=v2,color=v1))+
  geom_density()+
  facet_wrap(.~v1)

Output

enter image description here

Or if you only want one plot, here the code:

#Code for plot 2
df %>%
  ggplot(aes(x=v2,color=v1,group=v2))+
  geom_density()

Output

enter image description here

Or perhaps, using both geom_histogram() and geom_density():

#Code for plot 3
df %>%
  ggplot(aes(x=v2,color=v1,fill=v1))+
  geom_histogram()+
  geom_density(alpha=0.5)+
  facet_wrap(.~v1)

Output

enter image description here

Or if you want one plot:

#Code for plot 4
df %>%
  ggplot(aes(x=v2,color=v1,fill=v1,group=v1))+
  geom_histogram()+
  geom_density(alpha=0.5)

Output

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84
1

Perhaps, we can use geom_histogram

library(ggplot2)
ggplot(df1, aes(x = v2)) +
      geom_histogram() +
      facet_grid(~ v1)

enter image description here


Or another option is ggpubr

library(ggpubr)
gghistogram(df1, x = "v2", add = "mean", rug = TRUE, 
        fill = "v1", add_density = TRUE)

enter image description here


Or another option with geom_density and fill

ggplot(df1, aes(x = v2, fill = v1)) + 
       geom_density() + 
       facet_grid(~ v1)

enter image description here

data

df1 <- structure(list(v1 = c("t1", "t1", "t1", "t1", "t1", "t2", "t2", 
"t2", "t2", "t2"), v2 = c(2.2, 3.2, 2.2, 2.2, 4, 3.8, 2, 2.1, 
2, 3)), class = "data.frame", row.names = c(NA, -10L))
akrun
  • 874,273
  • 37
  • 540
  • 662