我在使用ggplot2
创建堆叠条形图时遇到了一个非常烦人的问题。虽然有几个类似的问题之前被问到过,但是在查看了示例代码后,我无法弄清楚我的错误在哪里。
我希望制作的图表按照Biogeographic.affinity
中的以下顺序堆叠条形:(从上到下= Bassian, Widespread, Torresian,和Eyrean)。 条形的颜色应该是:(Bassian=drakgrey,Widespread=lightgrey,Torresian=white,Eyrean=black)。
这是数据集的样子:
biogeo
Site Biogeographic.affinity Rank Number.of.species Total.Species Percent
1 A Bassian 1 1 121 0.8264463
2 A Eyrean 4 39 121 32.2314050
3 A Torresian 3 62 121 51.2396694
4 A Widespread 2 19 121 15.7024793
5 DD Bassian 1 1 128 0.7812500
6 DD Eyrean 4 46 128 35.9375000
7 DD Torresian 3 63 128 49.2187500
8 DD Widespread 2 18 128 14.0625000
9 E_W Bassian 1 1 136 0.7352941
10 E_W Eyrean 4 54 136 39.7058824
11 E_W Torresian 3 65 136 47.7941176
12 E_W Widespread 2 16 136 11.7647059
13 KS Bassian 1 2 145 1.3793103
14 KS Eyrean 4 63 145 43.4482759
15 KS Torresian 3 62 145 42.7586207
16 KS Widespread 2 18 145 12.4137931
17 Z_Ka Bassian 1 1 110 0.9090909
18 Z_Ka Eyrean 4 64 110 58.1818182
19 Z_Ka Torresian 3 31 110 28.1818182
20 Z_Ka Widespread 2 14 110 12.7272727
这是我目前为止写的代码(包括我尝试解决问题时的一些失败尝试)。
ggplot(data=biogeo, aes(x=Site, y=Percent, fill=Biogeographic.affinity)) + geom_bar(stat="identity", colour="black")+
scale_fill_grey() + ylab("Percent") + xlab("Location") +
theme_bw()+ theme(panel.grid.minor = element_blank())
这给出了基本的图表,但颜色和顺序仍然不正确。为了纠正顺序,我尝试了一些方法,但没有改变任何东西(感到沮丧)!
newone <- transform(biogeo, Biogeographic.affinity = factor(Biogeographic.affinity ), Rank = factor(Rank, levels = 1:4))
关于改变颜色,我已经尝试过了,似乎可以工作,但整个顺序看起来仍然不正确!
cols<- c("Bassian"="darkgrey","Widespread"="lightgrey", "Torresian"="white", "Eyrean"="black") #designates the colors of the bars
ggplot(data=newone, aes(x=Site, y=Percent, fill=Biogeographic.affinity)) + geom_bar(stat="identity", colour="black")+
scale_fill_manual(values = cols) + ylab("Percent") + xlab("Location") +
theme_bw()+ theme(panel.grid.minor = element_blank())
请帮忙。