简体   繁体   中英

Combination of stacked and side-by-side bar charts in R

In the lattice package of R it is possible to create stacked bar charts. I would like to have several stacked bars side by side similar to this one:

barchart( mpg ~ as.factor(gear), data=mtcars, groups=cyl, stack=F, horizontal=F, auto.key=T )

带盖条形的并排条形图

This is almost what I need. The problem is that the bars are layered, eg for the pink bar at the center there are 3 layered bars of approximately the same value (between 17 and 22). The bars are not stacked. The bar that is painted later covers bars painted earlier.

Would it also be possible to have different colors/textures for the stacked bars as well as for the side-by-side bars and an additional legend? The different levels in the stack come from an additional factor.

library(ggplot2)
ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) + geom_bar(stat = "identity", colour = "black") + facet_wrap(~gear)

在此处输入图片说明 mtcars$ID <- rownames(mtcars) ggplot(mtcars, aes(x = factor(gear), y = mpg, fill = factor(cyl), group = ID)) + geom_bar(stat = "identity", position = "dodge")

在此处输入图片说明

ggplot(mtcars, aes(x = factor(gear), y = mpg, colour = factor(cyl))) + geom_jitter()

在此处输入图片说明

ggplot(mtcars, aes(x = factor(gear), y = mpg, colour = factor(cyl))) + geom_boxplot()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM