I have a dataset of products per specialty and per contract type.
I would like to draw up the number of products per specialty and per contract type. I would like to see individual graphs per specialty (using facet_wrap) and individual bars (with different colors) for each contract.
This is what I have so far, but the "by contract" part doesn't work. What am I doing wrong?
spec <- c(rep(1, 5), rep(2,5), rep(3,5))
prod <- c(rep(15, 3), rep(22, 5), rep(35,2), rep(44, 5))
contract <- sample(c(0,1), replace=TRUE, size=15)
dat <- data.frame(spec=spec, prod=prod, contract = contract)
library(ggplot2)
ggplot(dat, aes(prod), fill=contract) +
geom_bar(position="dodge")+
facet_wrap(~spec, scales="free")
First of all, you should convert your input values into factors, as these are discrete values. This can be obtained with factor()
.
In the ggplot()
function, you have to use aes(x = contract)
if you want to have bars for each contract and fill = prod
within the aes()
for grouping by product.
If I understand your specification correct, this code should give you the desired solution:
library(ggplot2)
spec <- c(rep(1, 5), rep(2,5), rep(3,5))
prod <- c(rep(15, 3), rep(22, 5), rep(35,2), rep(44, 5))
contract <- sample(c(0,1), replace=TRUE, size=15)
dat <- data.frame(spec=factor(spec),
prod=factor(prod),
contract = factor(contract))
ggplot(dat) +
geom_bar(aes(contract, fill=prod), position = "dodge")+
facet_wrap(~spec, scales="free")
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.