给出这样的数据框:
sam<-data.table(title=c(rep("Cat",8),rep("Dog",4)),
fcat=c("A","B","C","B","B","C","C","B","C","B","B","C"),
fnum=c(seq(8,1),seq(4,1)),
labeltext=c("Pancakes","Muffins","Baursaq","Muffins","Muffins",
rep("Baursaq",3),"Muffins","Baursaq","Baursaq","Muffins"),
size=c(10,rep(1,11)))
sam
title fcat fnum labeltext size
1: Cat A 8 Pancakes 10
2: Cat B 7 Muffins 1
3: Cat C 6 Baursaq 1
4: Cat B 5 Muffins 1
5: Cat B 4 Muffins 1
6: Cat C 3 Baursaq 1
7: Cat C 2 Baursaq 1
8: Cat B 1 Baursaq 1
9: Dog C 4 Muffins 1
10: Dog B 3 Baursaq 1
11: Dog B 2 Baursaq 1
12: Dog C 1 Muffins 1
我想创建一个 x=标题、y=大小的条形图,由 fcat 填充,由 labeltext 标记,并按 fnum 降序排列。第一种方法无需对原始数据重新排序。在这里,我连接了标签文本,以检查顺序、大小和类别是否使用正确。
ggplot(sam)+
geom_bar(aes(x=factor(title), y=size,fill=fcat),
stat="identity", color="white", size=1)+
geom_text(aes(x=title, y=size,
label=(paste(labeltext,size,fnum,fcat, sep=" "))),
size = 3, position = position_stack(vjust = 0.5))+
ggtitle("Without ordering")
标签按需订购,但填充存在很大问题。
通过 fnum 重新排序填充:
ggplot(sam)+
geom_bar(aes(x=factor(title),
y=size,fill=reorder(fcat,fnum)),
stat="identity", color="white", size=1)+
geom_text(aes(x=title,y=size,
label=reorder(paste(labeltext,size,fnum,fcat,
sep=" "),fnum)),
size = 3, position = position_stack(vjust = 0.5))+
ggtitle("Ordered by fnum")
在这种情况下,酒吧按错误的填充物进行分组。例如,对于“Cat”,图表应绘制 1 个大小为 10 的蓝色条形,然后绘制 1 个绿色、1 个红色、2 个绿色、2 个红色、1 个绿色(如 labeltext 的类别中所示)。
我希望像原始数据一样删除该图。喜欢this https://stackoverflow.com/questions/18074511/ggplot2-stats-identity-and-stacking-colors-in-bar-plot-gives-striped-bar-cha家伙排在第一位。stat="identity"
没有按预期工作。
我尝试了多种方法重新排序,但没有什么帮助。我搜索了 ggplot2 标签中的 SO barplot 填充问题(超过 700 个帖子 o_O),并非常仔细地阅读了文档。尽管如此,到目前为止还没有找到答案。