2014-05-12 71 views
2

我正在尝试使用ggplot2重新创建由Tableau生成的此图。我已经足够了,但我似乎无法弄清楚如何添加颜色(其强度与利润量成正比)。BarPlot中的颜色

数据集是here

这里的情节我要复制

ggplot image

https://www.dropbox.com/s/wcu780m72a85lvi/Screen%20Shot%202014-05-11%20at%209.05.49%20PM.png

这里是我到目前为止的代码:

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

可以添加'+ theme_bw()+主题(strip.background = element_blank())+主题(panel.grid = element_blank())'要么溶液以除去栅&gray facet strip背景更接近您的Tableau图表。您也可以使用'gsub'在某些单词后面加一个'\ n',以确保它们被换行(即“Decaf Espresso”是ggplot2示例中的整行,而它在Tableau中则是分割的)。 wld避免了需要转动头来阅读ggplot解决方案中的标签:'coffee $ Product < - gsub(“(Cream | Espresso)”,“\ n \\ 1”,coffee $ Product)'(do在汇总之前) – hrbrmstr

+0

@hrbrmstr这是有用的信息。我想知道90度的标签 – jdharrison

回答

3

使用聚合函数。

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

+0

不错的使用'c(“#F37767”,“#9FC08D”,“#6BA862”,“#2B893E”,“#036227”)'颜色,它匹配OP的 – jdharrison

+0

@jdharrison,很好颜色发现。与这些编辑。 – Cole

+0

你的方法比我使用的方法简单得多。这应该是我想的答案。 – jdharrison

2

大概不会最好的方式做到这一点:

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) 

要得到的颜色c("#F37767", "#9FC08D", "#6BA862", "#2B893E", "#036227")我用ColorZilla插件。

enter image description here

+0

梦幻般的JD。非常非常感谢你。我很清楚,我永远无法想象这一个。 – user950899

+0

乐意帮忙.. – jdharrison