我该如何阻止ggplot自动安排我的图表? [英] how do I stop ggplot automatically arranging my graph?
问题描述
我使用ggplot包在R中创建了一个分组条形图。我使用了下面的代码:
$ b $ p
ggplot(completedDF,aes(year,value,fill = variable))+ geom_bar(position = position_dodge() ,图表=身份)
图表看起来像这样:
问题在于我希望1999-2008年的数据到最后。
有没有办法移动它?
ggplot
将遵循水平在一个因素。如果您没有订购您的因素,则认为订单是按字母顺序排列的。
如果您希望您的1999-2008模式结束,只需使用
<$ (x =已完成$年,
等级= c(1999-2002,2002-2005,2005-2008, 1999-2008))
例如:
library(ggplot2)
#创建示例数据集
set.seed(2014)
years_labels < -c(1999-2008,1999-2002,2002-2005,2005-2008)
variable_labels< -c(pointChangeVector,nonPointChangeVector,
onRoadChangeVector,nonRoadChangeVecto)
年< - rbinom(n = 1000,size = 3,prob = 0.3)
变量< - rbinom(n = 1000,size = 3,prob = 0.3)
year < - factor(x = years,levels = 0:3,labels = years_labels)
variable < - factor(x = variables,levels = 0:3,labels = variable_labels)
完成< - data.frame(year,variable)
#plot
ggplot(compl eted,aes(x = year,fill = variable))+ geom_bar(position = position_dodge())
#更改订单
完成$ year < - 因子(x =完成$ year,
levels = c(1999-2002,2002-2005,2005-2008 ),1999-2008))
ggplot(已完成,aes(x = year,fill = variable))+ geom_bar(position = position_dodge())
另外,使用这个函数的另一个好处是,您也可以将结果以良好顺序显示给其他函数,如 summary
或情节
。
它有帮助吗?
I made a grouped barchart in R using the ggplot package. I used the following code:
ggplot(completedDF,aes(year,value,fill=variable)) + geom_bar(position=position_dodge(),stat="identity")
And the graph looks like this:
The problem is that I want the 1999-2008 data to be at the end.
Is there anyway to move it?
Thanks any help appreciated.
ggplot
will follow the order of the levels in a factor. If you didn't ordered your factor, then it is assumed that the order is alphabetical.
If you want your "1999-2008" modality to be at the end, just reorder your factor using
completed$year <- factor(x=completed$year,
levels=c("1999-2002", "2002-2005", "2005-2008", "1999-2008"))
For example :
library(ggplot2)
# Create a sample data set
set.seed(2014)
years_labels <- c( "1999-2008","1999-2002", "2002-2005", "2005-2008")
variable_labels <- c("pointChangeVector", "nonPointChangeVector",
"onRoadChangeVector", "nonRoadChangeVecto")
years <- rbinom(n=1000, size=3,prob=0.3)
variables <- rbinom(n=1000, size=3,prob=0.3)
year <- factor(x=years , levels=0:3, labels=years_labels)
variable <- factor(x=variables , levels=0:3, labels=variable_labels)
completed <- data.frame( year, variable)
# Plot
ggplot(completed,aes(x=year, fill=variable)) + geom_bar(position=position_dodge())
# change the order
completed$year <- factor(x=completed$year,
levels=c("1999-2002", "2002-2005", "2005-2008", "1999-2008"))
ggplot(completed,aes(x=year, fill=variable)) + geom_bar(position=position_dodge())
Furthermore, the other benefit of using this is you will have also your results in a good order for others functions like summary
or plot
.
Does it help?
这篇关于我该如何阻止ggplot自动安排我的图表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!