分组的barplot:顺序x轴&保持恒定的酒吧宽度,以防万一缺少水平 [英] grouped barplot: order x-axis & keep constant bar width, in case of missing levels
问题描述
以下是我的脚本(示例源自
我想要的是在'拒绝'的条件下订购我的barplot ,所有'改进'不会插在中间。这里是我想得到的(在一些svg编辑之后):
因此,现在所有的下降条件都被排序,并且改进条件出现。此外,理想情况下,即使条件未表示为值(例如,Bla没有Decline值),条形将全部处于相同宽度。
关于如何在不使用SVG编辑器的情况下做到这一点的想法?非常感谢!
首先,让我们填入您的data.frame,并填写像这样的缺失组合。
library(dplyr)
Animals2 < - expand.grid(Category = unique(Animals $ Category),Reason = unique(Animals $ Reason))% >%data.frame%>%left_join(Animals)
然后您可以创建一个排序变量对于x-scale:
myorder< - Animals2%>%filter(类别==拒绝)%> ;%arrange(desc(Species))%>%。$ Reason%>%as.character
然后绘图:
ggplot(Animals2,aes(x = Reason,y = Species,fill = Category))+
geom_bar(stat =identity,position =dodge)+ scale_x_discrete(limits = myorder)
Here is my script (example inspired from here and using the reorder
option from here):
library(ggplot2)
Animals <- read.table(
header=TRUE, text='Category Reason Species
1 Decline Genuine 24
2 Improved Genuine 16
3 Improved Misclassified 85
4 Decline Misclassified 41
5 Decline Taxonomic 2
6 Improved Taxonomic 7
7 Decline Unclear 10
8 Improved Unclear 25
9 Improved Bla 10
10 Decline Hello 30')
fig <- ggplot(Animals, aes(x=reorder(Animals$Reason, -Animals$Species), y=Species, fill = Category)) +
geom_bar(stat="identity", position = "dodge")
This gives the following output plot:
What I would like is to order my barplot only on condition 'Decline', and all the 'Improved' would not be inserted in the middle. Here is what I would like to get (after some svg editing):
So now all the whole 'Decline' condition is sorted and the 'Improved' condition comes after. Besides, ideally, the bars would all be at the same width, even if the condition is not represented for the value (e.g. "Bla" has no "Decline" value).
Any idea on how I could do that without having to play with SVG editors? Many thanks!
First let's fill your data.frame with missing combinations like this.
library(dplyr)
Animals2 <- expand.grid(Category=unique(Animals$Category), Reason=unique(Animals$Reason)) %>% data.frame %>% left_join(Animals)
Then you can create an ordering variable for the x-scale:
myorder <- Animals2 %>% filter(Category=="Decline") %>% arrange(desc(Species)) %>% .$Reason %>% as.character
An then plot:
ggplot(Animals2, aes(x=Reason, y=Species, fill = Category)) +
geom_bar(stat="identity", position = "dodge") + scale_x_discrete(limits=myorder)
这篇关于分组的barplot:顺序x轴&保持恒定的酒吧宽度,以防万一缺少水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!