问题描述
我使用 ggplot
绘制了一个分面图,这里是图
I plotted a facet plot using ggplot
and here is the plot
我遇到的问题是,刻面(标签)按字母顺序排序(例如:E1、E10、E11、E13、E2、E3、I1、I10、I2)但我需要它们是像 E1 这样的自定义订单,I1、E2、I2、E3、E10、I10、E11、E13.
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.
我该怎么做?
推荐答案
不要依赖 factor()
或 ggplot
内部施加的默认级别顺序如果您提供的分组变量不是一个因素.自己明确设置级别.
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)
产生:
这篇关于如何更改ggplot中的facet标签的顺序(自定义facet wrap标签)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!