0

I currently have data that tell me blood pressure by age for those 10-18. I would like to create a density plot for each age similar to a violin plot.

It would sort of look like this, but with just the density plots.

The key is to get a histogram for each age then flip it and plot it wherein the x-axis is age and the y axis is blood pressure. I feel like I've seen this done before, but I can't remember where.

Thanks for any help!

tonytonov
  • 25,060
  • 16
  • 82
  • 98
  • Please make a reproducible example: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example. – tonytonov May 04 '16 at 08:28

2 Answers2

1

I think this should do the trick:

# load libraris
  library(ggplot2)
  library(ggthemes)

# load data
  data(iris)


# Plot
  ggplot(data = iris) +
    geom_density( aes(x=Sepal.Length), fill="red", color="red") +
    facet_grid(.~Species) +
    theme_minimal() +
    coord_flip()

enter image description here

You could also use geom_violin:

  ggplot(data = iris) +
    geom_violin( aes(x=Species, y=Sepal.Length), fill="red", color="red") +
    geom_jitter( aes(x=Species, y=Sepal.Length), fill="gray", color="gray") +
    theme_minimal() 

enter image description here

In any case, your variable on blood pressure is equivalent to Sepal.Length presented here, while your age categorical variable is equivalent to Species as a factor().

rafa.pereira
  • 13,251
  • 6
  • 71
  • 109
0

The key to this may be the combination of a couple of features:

  1. Use the pressure as your x-axis and then flip the coordinate axis.
  2. Use age to make the facit grid dependent on it. Keep in mind to make age a factor beforehand!

Here is a minimal example with some random generated data for people between 25 and 30 years old and blood pressure between 50 and 150 (no idea how realistic that is):

data <- data.frame(age=round(runif(1000, 25, 30)), pressure=round(runif(1000, 50, 150)))
data$age <- factor(data$age)

library(ggplot2)
ggplot(data, aes(x=pressure)) +
  geom_density() +
  coord_flip() +
  facet_grid(.~age)

enter image description here

Make42
  • 12,236
  • 24
  • 79
  • 155