ggplot2:geom_bar填充颜色;如何更改为不同的数据分组

时间:2016-07-17 21:55:34

标签: r ggplot2 colors geom-bar

我有以下数据集显示会计期间,产品和交易总额:

app$FISCAL_PERIOD <-c(201604,201604,201604,201605,201605,201605,201606,201606,201606,201607,201607,201607,201608,201608,201608,201609,201609,201610,201610,201611,201611)

app$Product <- c("Product 1","Product 3","Other","Product 1","Product 3","Other","Product 1","Product 3","Other","Product 1","Product 3","Other","Product 1","Product 3","Other","Product 2","Product 3","Product 2","Product 3","Product 2","Product 3")

app$sum_trans<-c(78,23410,1946,84,29532,417,16,30364,129,305,32386,584,424,20873,274,20,20929,470,19261,10,6131)

我在ggplot2中将其绘制为躲闪条形图。 Ggplot会自动为每个填充分配颜色,以便每个会计期间的颜色都不同。

ggplot(data = app, aes(x = Product, y = sum_trans, fill = as.factor(FISCAL_PERIOD))) + 
    geom_bar(stat="identity", position="dodge", colour="black")

Plot drawn by ggplot code above

我需要的是显示每种产品具有相同的颜色和填充变量而不影响图表。 即我希望所有产品1会计期间数据为一种颜色,所有产品3会计期间数据为另一种颜色。

1 个答案:

答案 0 :(得分:0)

您可以将填充变量设置为product,因为它定义了您想要的颜色,并将另一个组变量指定为FISCAL_PERIOD,这样每个栏仍将按年分段:

ggplot(data = app, aes(x = Product, y = sum_trans, fill = Product, group = FISCAL_PERIOD)) + 
   geom_bar(stat="identity", position="dodge", colour="black")

enter image description here