converting boxplots to densities in ggplot2 in R
ggplot2, graphics, r
Solution
Something like this? For both `histogram` and `density` plots, the `y` variable is `count`. So, you've to plot `x = Petal.Length` whose frequency (for that given binwidth) will be plotted in the y-axis. Just use `fill=Species` along with `x=Petal.Length` to give colours by `Species`.
For `histogram`:
ggplot(iris, aes(x=Petal.Length, fill=Species)) +
geom_histogram(position="identity") + coord_flip()
For `density`:
ggplot(iris, aes(x=Petal.Length, fill=Species)) +
geom_density(position="identity") + coord_flip()
Edit: Maybe you're looking for `facetting`??
ggplot(mpg, aes(x=displ, fill=factor(cyl))) +
geom_density(position="identity") +
facet_wrap( ~ manufacturer, ncol=3)
Gives:
Edit: Since, you don't want `facetting`, the only other way I can think of is to create a separate group by pasting `manufacturer` and `cyl` together:
dd <- mpg
dd$grp <- factor(paste(dd$manufacturer, dd$cyl))
ggplot(dd, aes(x=displ)) +
geom_density(aes(fill=grp), position="identity")
gives:
Problem
I have the following ggplot2 plot: ``` ggplot(iris) + geom_boxplot(aes(x=Species, y=Petal.Length, fill=Species)) + coord_flip() ``` I would like to instead plot this as horizontal density plots or histograms, meaning have density line plots for each species or histograms instead of boxplots. This does not do the trick: ``` > ggplot(iris) + geom_density(aes(x=Species, y=Petal.Length, fill=Species)) + coord_flip() Error in eval(expr, envir, enclos) : object 'y' not found ``` for simplicity I used `Species` as the `x` variable and as the `fill` but in my actual data the X axis represents one set of conditions and the fill represents another. Though that should not matter for plotting purposes. I'm trying to make it so the X axis represents different conditions for which the value `y` is plotted as a density/histogram instead of boxplots. edit this is better illustrated with a variable that has two factor-like variables like Species. In the `mpg` dataset, I want to make a density plot for each manufacturer, plotting the distribution of `displ` for each `cyl` value. The x-axis (which is vertical in flipped coordinates) represents each manufacturer, and value being histogrammed is `displ`, but for each manufacturer, I want as many histograms as there are `cyl` values for that manufacturer. Hope this is clearer. I know that this doesn't work because `y=` expects counts. ``` ggplot(mpg, aes(x=manufacturer, fill=cyl, y=displ)) + geom_density(position="identity") + coord_flip() ``` The closest I get is: ``` > ggplot(mpg, aes(x=displ, fill=cyl)) + + geom_density(position="identity") + facet_grid(manufacturer ~ .) ``` But I don't want different grids, I'd like them to be different entries in the same plot like in the histogram case.