Question

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

ggplot image

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))
Was it helpful?

Solution

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))

Pretty pic

OTHER TIPS

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.

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top