this is an extension to the question I asked previously:
How to extract the density value from ggplot in r
This fruit dataset is in fact the data for country A, and now that I have another dataset for country B. I would like to compare their values. However, the density plot (the y-axis) for fruit apple for country A and country B are different, where country A has its highest density around 0.8 and country B has its at around 0.4.
Q. Country B has similar curve but its highest density value of the y-axis is only 0.4. So how can I compare them?
Code for minimal example:
library(ggplot2)
set.seed(1234)
df = data.frame(
fruits = factor(rep(c("Orange", "Apple", "Pears", "Banana"), each = 200)),
weight = round(c(rnorm(200, mean = 55, sd=5),
rnorm(200, mean=65, sd=5),
rnorm(200, mean=70, sd=5),
rnorm(200, mean=75, sd=5)))
)
dim(df) #[1] 800 2
ggplot(df, aes(x = weight)) +
geom_density() +
facet_grid(fruits ~ ., scales = "free", space = "free")
g = ggplot(df, aes(x = weight)) +
geom_density() +
facet_grid(fruits ~ ., scales = "free", space = "free")
p = ggplot_build(g)
sp = split(p$data[[1]][c("x", "density")], p$data[[1]]$PANEL)
apple_df = sp[[1]]
sum(apple_df$density ) # this is equal to 10.43877 but i want it to be one