简体   繁体   中英

Density over histogram using ggplot2

I have "long" format data frame which contains two columns: first col - values, second col- sex [Male - 1/Female - 2]. I wrote some code to make a histogram of entire dataset (code below).

ggplot(kz6, aes(x = values)) + 
  geom_histogram()

However, I want also add a density over histogram to emphasize the difference between sexes ie I want to combine 3 plots: histogram for entire dataset, and 2 density plots for each sex. I tried to use some examples ( one , two , three , four ), but it still does not work. Code for density only works, while the combinations of hist + density does not.

density <- ggplot(kz6, aes(x = x, fill = factor(sex))) + 
  geom_density()

both <- ggplot(kz6, aes(x = values)) + 
  geom_histogram() +
  geom_density()

both_2 <- ggplot(kz6, aes(x = values)) + 
  geom_histogram() +
  geom_density(aes(x = kz6[kz6$sex == 1,]))

PS some examples contains y=..density.. what does it mean? How to interpret this?

To plot a histogram and superimpose two densities, defined by a categorical variable, use appropriate aesthetics in the call to geom_density , like group or colour .

ggplot(kz6, aes(x = values)) +
  geom_histogram(aes(y = ..density..), bins = 20) +
  geom_density(aes(group = sex, colour = sex), adjust = 2)

在此处输入图片说明

Data creation code.

I will create a test data set from built-in data set iris .

kz6 <- iris[iris$Species != "virginica", 4:5]
kz6$sex <- "M"
kz6$sex[kz6$Species == "versicolor"] <- "F"
kz6$Species <- NULL
names(kz6)[1] <- "values"
head(kz6)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM