问题描述
我正在使用geom_bar函数通过以下示例示例创建条形图。 面积较小的颜色条(例如0.006和0.003)不会以升序显示,而是在图中显示较高的值。 有人知道它为什么会发生以及如何解决吗? 谢谢
library(ggplot2)
ID <- c(1,1,2,3,3)
Type <- c("Bc","Ea","Ra","Lr","Ram")
Area <- c(0.15,0.11,0.0066,0.0037,0.088)
data.Table <- data.frame(ID,Type,Area )
p <- ggplot(dataTable)+
geom_bar(aes(fill=Type,y=Area,x=ID),stat="identity")
print(p)
解决方法
要按区域升序对堆叠的条形重新排序,可以使用reorder(Type,-Area)
:
library(ggplot2)
ID <- c(1,1,2,3,3)
Type <- c("Bc","Ea","Ra","Lr","Ram")
Area <- c(0.15,0.11,0.0066,0.0037,0.088)
data.Table <- data.frame(ID,Type,Area )
p <- ggplot(data.Table)+
geom_bar(aes(fill=reorder(Type,-Area),y=Area,x=ID),stat="identity")
print(p)
编辑如果y轴应显示每个条形图的Area值,即,条形图不应堆叠在彼此的顶部,但另外,不应将条形图闪避,则唯一我能想到的选择是使用position="identity"
(或position = position_dodge(width = .1)
覆盖条形和覆盖层的混合)覆盖条形图。在这种情况下,我们必须对数据集进行排序,以使面积较小的观测值位于每个ID的末尾(可以通过data.Table[order(ID,]
实现)。此外,在这种情况下,我们不必重新排序Type:
library(ggplot2)
ID <- c(1,Area )
data.Table01<- data.Table[order(ID,]
ggplot(data.Table01) +
geom_bar(aes(fill=Type,stat="identity",position = "identity")