# ggplot2 练习杂记二 EXCEL 分组堆积条形图

Excel中图表如下：

R中图形如下：

R中代码如下：

`channel <- read.xlsx("c:/myR/channel.xlsx",sheetName="Sheet2",encoding="UTF-8")ggplot(channel, aes(x = as.numeric(interaction(Left,Name)), y = Amount, fill =Type,group=Name)) #把x轴的显示的内容处理下分组序号+ geom_bar(stat = "identity")+ scale_x_continuous(breaks=c(1.5,3.5,5.5,7.5),labels=c("A","B","C","D"))#主要靠这里来定制X轴的显示内容，+theme( panel.grid.major=element_blank(),panel.grid.minor=element_blank())+coord_flip() #翻转如果不加这句则图像为柱状图`

Name

Type

Amount

Left

A

842

L

A

96,907

L

A

3,250

R

A

94,541

R

B

493

L

B

58,210

L

B

381

R

B

58,321

R

C

1,215

L

C

56,999

L

C

3,373

R

C

54,540

R

D

1,293

L

D

56,699

L

D

6,206

R

D

51,785

R

---------------------------------------------------------------------------------------------------------------------------------------------

update 2015-07-16

`ggplot(data = channel2, aes(x = Left, y = Amount, fill = factor(Type) ,order = as.numeric(factor(channel2\$Type,levels=c("期初库存","采购","期末库存","销售"))) ))  + geom_bar(stat = "identity", width = 1, position = "stack" ) + facet_grid(. ~ Name,scales = "free_x") + theme(axis.text.x =element_blank())#数据还是最上面的数据，对数据按Name进行分片，然后x轴绑定Left字段，再在最后将X轴上显示的文字取消.#order = as.numeric(factor(channel2\$Type,levels=c("期初库存","采购","期末库存","销售")))    是设置堆积图的顺序`

------------------------------------------------------------------------------------------------------

update

`ggplot(data = channel2, aes(x =factor(Left,levels=c("R","L")), y = Amount, fill = factor(Type) ,order = as.numeric(factor(channel2\$Type,levels=c("期初库存","采购","期末库存","销售"))) ))+ geom_bar(stat = "identity", width = 1, position = "stack" )+ theme(axis.text.x =element_blank(),axis.text.y =element_blank()) #不显示Y，X轴的标签+coord_flip() #翻转+facet_grid(Name~.) #分片（fact_grid(Name~.) 分片按行显示如上图，（facet_grid(.~Name) 分片按列显示，如上上图 ^^)`