Reputation: 63
I'm trying to recreate this graph produced by Tableau using ggplot2
. I've gotten far enough but I can't seem to figure out how to add color (whose intensity is proportional to the amount of profit).
The dataset is here
Here's the plot I want to replicate
https://www.dropbox.com/s/wcu780m72a85lvi/Screen%20Shot%202014-05-11%20at%209.05.49%20PM.png
Here's my code so far:
ggplot(coffee,aes(x=Product,weight=Sales))
+geom_bar()+facet_grid(Market~Product.Type,scales="free_x",space="free")
+ylab("Sales")+theme(axis.text.x=element_text(angle=90))
Upvotes: 2
Views: 237
Reputation: 1769
Using the aggregate function.
library(ggplot2)
coffee <- read.csv('CoffeeChain.csv')
agg <- aggregate(cbind(Profit, Sales) ~ Product+Market+Product.Type, data=coffee, FUN=sum)
ggplot(agg, aes(x=Product, weight=Sales, fill=Profit), stat="identity") +
geom_bar() +
scale_fill_gradientn(colours=c("#F37767", "#9FC08D", "#6BA862", "#2B893E", "#036227")) +
facet_grid(Market~Product.Type, scales="free_x", space="free") +
ylab("Sales") +
theme(axis.text.x=element_text(angle=90))
Upvotes: 3
Reputation: 30425
Probably not the best way to do it:
require(ggplot2)
aggProfit <- ave(coffee$Profit, coffee$Product.Type, coffee$Product, coffee$Market, FUN=sum)
coffee$Breaks<- cut(aggProfit, c(seq(-8000, 25000, 5000), max(aggSales)), dig.lab = 10)
appcolors <- c("#F37767", "#9FC08D", "#6BA862", "#2B893E", "#036227")
gg <- ggplot(coffee,aes(x=Product,weight=Sales, fill = Breaks))+
geom_bar()+facet_grid(Market~Product.Type,scales="free_x",space="free")+
ylab("Sales")+theme(axis.text.x=element_text(angle=90)) +
scale_fill_manual(values=colorRampPalette(appcolors)( length(levels(coffee$Breaks)) ))
plot(gg)
To get the colors c("#F37767", "#9FC08D", "#6BA862", "#2B893E", "#036227")
I used the ColorZilla plugin.
Upvotes: 2