0

I have a histogram and want to display a density plot line or area over it. It does not work with the following code.

The histogram is displayed the way i want but the geom_density() does not seem to work Note, i changed the column names to make it anonymous here on stack.

plot <- ggplot(data=df, aes(x=DFCOLUMN)) +
                  geom_histogram(binwidth=10, color="#0000FF", fill="white") +
                  geom_density(alpha=.5, fill="#FF6666") +
                  facet_grid(. ~ SOME OTHER COLUMN) +
                  coord_cartesian(xlim=c(0,600)) +
                  ggtitle("COLUMNAME") +
                  theme(panel.background = element_blank())

Can you come up with a fix?

Thank you

corkinabottle
  • 141
  • 1
  • 7

1 Answers1

1

Does this help? Will remove if not, just too long for comment :)

library(ggplot2)
# http://www.sthda.com/english/wiki/ggplot2-density-plot-quick-start-guide-r-software-and-data-visualization
# https://stackoverflow.com/questions/6957549/overlaying-histograms-with-ggplot2-in-r

x <- data.frame(V1 = rnorm(1000, 100,40))

### Density on y axis
ggplot(x, aes(x = V1)) +
  geom_histogram(aes(y = ..density..), colour = "black", fill = "white") +
  geom_density(alpha = .2, fill = "#FF6666")

### count on y axis
ggplot(x, aes(x = V1)) +
  geom_histogram(colour = "black", fill = "white") +
  geom_density(aes(y = ..count..), alpha = .2, fill = "#FF6666")
QAsena
  • 603
  • 4
  • 9
  • Thank you QAsena. the second code "### count on y axis" helps out. It shows a density plot now. Only one issue remains: Can I change the yscale of the density plot so that it is displayed more pronounced across the Y axis? It currently obviously follows the histogram distribution but is rather small in the bottom left corner. I unfortunately can't post a picture in the comment here. – corkinabottle Jan 02 '21 at 09:49
  • mm I'm not sure about that. `ggplot` doesn't agree with dual axes (https://stackoverflow.com/questions/3099219/ggplot-with-2-y-axes-on-each-side-and-different-scales). @stefan? Maybe you could update the image in the question @corkinabottle? – QAsena Jan 02 '21 at 09:56
  • Oh that is a bit on the small side... I'm not sure if there is a correct way to increase the size since it should be correct given the data. I updated my answer with an example that shows more difference between the `..count..` and `..density..` arguments but it probably doesn't quite solve the problem... sorry! – QAsena Jan 02 '21 at 10:14
  • I found the issue by the way. I set the binwidth to 10 which produces this small density chart. If you change it to e.g. 1, the density chart looks more fitting to the actual bars. – corkinabottle Jan 02 '21 at 10:37