如何更改ggplot中facet标签的顺序(自定义facet wrap标签) [英] How to change the order of facet labels in ggplot (custom facet wrap labels)
问题描述
你好我在R中使用ggplot绘制了一个方面图,这里是图
我遇到的问题是,facet(标签) (例如:E1,E10,E11,E13,E2,E3,I1,I10,I2),但我需要它们是像E1,I1,E2,I2,E3,E10,I10,E11, E13。
我该怎么做?
t依赖于由 factor()
或由内部由 ggplot
施加的默认级别,如果您提供的分组变量是不是的一个因素。
dat < - data.frame(x = runif(100),y = runif(100 ),
group = gl(5,20,labels = LETTERS [1:5]))
head(dat)
with(dat,levels(Group))
如果我想要这些乱七八糟的东西呢?
<$ p $ ($)
$($ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ b
为此,请根据需要设置各个级别。
set.seed( 1)#重置种子,所以我得到
dat < - 内(dat,Group < - factor(Group,levels = sample(levels(Group))))
之上的随机顺序形式(dat,levels(Group))
现在我们可以用这个按顺序绘制面板 需要:
require(ggplot2)
p < - ggplot(dat,aes (x = x))+ geom_bar()
p + facet_wrap(〜Group)
产生:
Hi I plotted a facet plot using ggplot in R and here is the plot
The problem I have is, The facets(labels) are sorted alphabetically (Ex: E1, E10, E11,E13, E2, E3, I1, I10, I2) but I need them to be a custom order like E1, I1, E2, I2, E3, E10, I10, E11, E13.
How can I do that ?
Don't rely on the default ordering of levels imposed by factor()
or internally by ggplot
if the grouping variable you supply is not a factor. Set the levels explicitly yourself.
dat <- data.frame(x = runif(100), y = runif(100),
Group = gl(5, 20, labels = LETTERS[1:5]))
head(dat)
with(dat, levels(Group))
What if I want them in this arbitrary order?
set.seed(1)
with(dat, sample(levels(Group)))
To do this, set the levels the way you want them.
set.seed(1) # reset the seed so I get the random order form above
dat <- within(dat, Group <- factor(Group, levels = sample(levels(Group))))
with(dat, levels(Group))
Now we can use this to have the panels drawn in the order we want:
require(ggplot2)
p <- ggplot(dat, aes(x = x)) + geom_bar()
p + facet_wrap( ~ Group)
Which produces:
这篇关于如何更改ggplot中facet标签的顺序(自定义facet wrap标签)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!