修复ggplot中构面的顺序 [英] Fixing the order of facets in ggplot
问题描述
数据:
类型大小金额
T 50%48.4
F 50%48.1
P 50%46.8
T 100%25.9
F 100%26.0
P 100%24.9
T 150%21.1
F 150%21.4
P 150%20.1
T 200%20.8
F 200%21.5
P 200%16.5
我需要使用ggplot(x轴 - >type,y轴 - >amount,group bysize)绘制上述数据的条形图。当我使用下面的代码时,我没有按照数据中显示的顺序获取变量type和size。请看图。我已经使用了下面的代码。
ggplot(temp,aes(type,amount,fill = type,group = type,shape = type,facets = size) )+ geom_bar(width = 0.5,position = position_dodge(width = 0.6))+ facet_grid(。〜size)+ theme_bw()+ scale_fill_manual(values = c(darkblue,steelblue1,steelblue4),labels = c(T,F,P))
。
为了解决订单问题,我使用了变量类型的因子方法使用以下内容。
temp $ new = factor(temp $ type,levels = c(T,F ,P),标签= c(T,F,P))
然而,现在我不知道如何修改变量size的顺序。应该是50%,100%。 150%和200%。
通过以下方式将您的大小变为数据框的一个因素:
temp $ size_f =因子(temp $ size,levels = c('50%','100%','150%','200%') )
然后更改 facet_grid(。〜size)
to facet_grid(。〜size_f)
然后绘制:
现在图形按照正确的顺序排列。 p>
Data:
type size amount
T 50% 48.4
F 50% 48.1
P 50% 46.8
T 100% 25.9
F 100% 26.0
P 100% 24.9
T 150% 21.1
F 150% 21.4
P 150% 20.1
T 200% 20.8
F 200% 21.5
P 200% 16.5
I need to plot a bargraph of the above data using ggplot (x-axis -> "type", y-axis -> "amount", group by "size"). When I used the following code, I am not getting the variable "type" and as well as "size" in the order shown in the data. Please see the figure. I have used the following code for that.
ggplot(temp, aes(type, amount , fill=type, group=type, shape=type, facets=size)) + geom_bar(width=0.5, position = position_dodge(width=0.6)) + facet_grid(.~size) + theme_bw() + scale_fill_manual(values = c("darkblue","steelblue1","steelblue4"), labels = c("T", "F", "P"))
.
For fixing the order issue, I have used a factor method for the variable "type" using the following. Please see the figure also.
temp$new = factor(temp$type, levels=c("T","F","P"), labels=c("T","F","P"))
However, now I don't know how to fix the order for the variable "size". It should be 50%, 100%. 150%, and 200%.
Make your size a factor in your dataframe by:
temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))
Then change the facet_grid(.~size)
to facet_grid(.~size_f)
Then plot:
The graphs are now in the correct order.
这篇关于修复ggplot中构面的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!