0

I try to plot both geom_histogram and geom_density in one figure. When I plot the two separate from each other I get for each the output I want (histogram and density plot) but when I try combining them, only the histogram is showed (regardless of which order of the histogram/density in the code).

My code looks like this:

ggplot(data=Stack_time, aes(x=values))+geom_density(alpha=0.2, fill="#FF6666")+
  geom_histogram(binwidth = 50, colour="black", fill="#009454")

I do not receive any error message, but the geom_density is never shown in combination with the geom_histogram.

mischva11
  • 2,811
  • 3
  • 18
  • 34
Andrea
  • 41
  • 8
  • 2
    please provide a [minimum reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). You question can be solved a lot easier with information about your database – mischva11 Jun 02 '19 at 14:00
  • 1
    also my guess: Your data is not normalized. Density plots have an y axis from 0-1, if your data is much higher, the density plot is far to tiny, also add `alpha=0.5` to your `geom_histogram` – mischva11 Jun 02 '19 at 14:03
  • You are right. The density plot is much too small on the y-axis to be visible. Thank you for this clarification! – Andrea Jun 02 '19 at 14:10

2 Answers2

0

Since you did not provide any data here a solution based on mtcars:

Your code is nearly correct. You need to add an alpha value to your histogram, so you can see the density. But also you need to scale your data, since the density plot is between the range of 0 and 1. If you got data values larger then 1, the density plot can be tiny and you can't see it. With the function scale_data as defined as follows, i scale my data to the range of 0-1

df=mtcars
scale_data <- function(x){(x-min(x))/(max(x)-min(x))}
df$mpg2 <- scale_data(df$mpg)
library(ggplot2)
ggplot(data=df, aes(x=mpg2))+geom_density(alpha=0.2, fill="#FF6666")+
  geom_histogram(binwidth = 50, colour="black", fill="#009454", alpha = 0.1)

this gives the expected output: plot

you can adjust this solution to your needs. Just scale the data or the density plot to the data

mischva11
  • 2,811
  • 3
  • 18
  • 34
0

This should do the job, approximately:

data.frame(x=rnorm(1000)) %>% ggplot(aes(x, ..density..)) + geom_histogram(binwidth = 0.2, alpha=0.5) + geom_density(fill="red", alpha=0.2)

MR_MPI-BGC
  • 265
  • 3
  • 11