考虑一个数据框的数值变量中的顺序,如何在ggplot2图中着色条

时间:2013-11-08 18:21:53

标签: r ggplot2

大家好我正在尝试制作一个带有特殊元素的ggplot图形来为图形增加价值。我有下一个数据框:

Name    x
1   33374984
2   33209955
3   30250000
4   25897811
5   14995677
6   8200000
7   7878540
8   7571275
9   7188469
10  6756588
11  6592099
12  6538284
13  6248395
14  6116285
15  6045148
16  5745422
17  5670931
18  5494094
19  5282317
20  4695526
21  4641434
22  4595977
23  4572251
24  4535916
25  4506470
26  4445051
27  4444925
28  4393253
29  4383303
30  4349352
31  4278734
32  4134470
33  4102491
34  4010763
35  3589238
36  3573466
37  3524591
38  3497869
39  3340105
40  3292353
41  3234672
42  3217727
43  3202363
44  3170645
45  3119682
46  3092471
47  3033967
48  3000145
49  2994306
50  2943389
51  2940969
52  2936803
53  2923212
54  2884965
55  2863525
56  2846172
57  2839577
58  2819895
59  2809083
60  2804884
61  2752059
62  2750962
63  2740161
64  2718946
65  2580859
66  2580822
67  2553712
68  2490213
69  2425135
70  2406000
71  2405486
72  2387143
73  2384597
74  2381402
75  2372381
76  2308623
77  2299046
78  2287879
79  2260205
80  2245436
81  2208582
82  2203883
83  2176060
84  2169769
85  2136766
86  2121242
87  2115891
88  2106713
89  2084986
90  2049367
91  2031410
92  2023409
93  2015622
94  1999140
95  1901045
96  1900000
97  1891783
98  1863410
99  1859789
100 1851046

我使用以下代码制作了一个简单的ggplot条形图:

png(filename = "Delta.png", width = 800, height = 1000)
Delta=ggplot(DeltaPBO)+
  geom_bar(aes(x=Name,y=x,fill=x),
           stat='identity',position='dodge')+theme(axis.text.x=element_text(angle=80,hjust=1,vjust=1,colour="grey20",face="bold",size=12),axis.text.y=element_text(colour="grey20",face="bold",hjust=1,vjust=0.8),axis.title.x=element_text(colour="grey20",face="bold",size=15),axis.title.y=element_text(colour="grey20",face="bold",size=15))+xlab('Cliente')+ylab('Total')+ ggtitle("My graph")+theme(plot.title = element_text(lineheight=3, face="bold", color="black", size=29))
print(Delta)
dev.off()

我得到了这张图: enter image description here 我的问题是下一个x按降序排列,我想在图形中显示每25个观测值的不同条形颜色,例如观察1到25应该是黄色的,因为它们的值高于观察值26到50 ;观测26至50应该有绿色,因为它们高于观测值51至75;观测51到75应该有蓝色,因为它们高于观测值76到100,最后观测值76到100应该有红色,因为它们有次要值。

我想在R中做这个,但我对ggplot知之甚少。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您可以为数据中的每25个观察值添加包含分组名称的新变量。然后使用这个新变量来填充条形。 scale_fill_manual()根据需要设置填充颜色。

DeltaPBO$group<-rep(c("A","B","C","D"),each=25)
ggplot(DeltaPBO)+
  geom_bar(aes(x=Name,y=x,fill=as.factor(group)),
           stat='identity',position='dodge')+
  scale_fill_manual(values=c("yellow","green","blue","red"))

enter image description here