数据:
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
我需要使用ggplot(x轴 - >“type”,y轴 - >“amount”,group by“size”)绘制上述数据的条形图。当我使用下面的代码时,我没有按照数据中显示的顺序获得变量“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"))
。
为了解决订单问题,我使用了以下的变量“type”的因子方法。请看图。
temp$new = factor(temp$type, levels=c("T","F","P"), labels=c("T","F","P"))
但是,现在我不知道如何修改变量“size”的顺序。它应该是50%,100%。 150%和200%。
答案 0 :(得分:91)
通过以下方式使您的尺寸成为数据框中的一个因素:
temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))
然后将facet_grid(.~size)
更改为facet_grid(.~size_f)
然后绘制:
现在图表的顺序正确。
答案 1 :(得分:11)
这里有几个很好的解决方案。
类似于 Harpal 的答案,但在方面内,因此不需要对基础数据或预绘图操作进行任何更改:
# Change this code:
facet_grid(.~size) +
# To this code:
facet_grid(~factor(size, levels=c('50%','100%','150%','200%')))
这很灵活,可以在您更改分面元素时为任何变量实现,无需对所需数据进行底层更改。
答案 2 :(得分:2)
甚至更少的操纵:
facet_grid(~fct_relevel(size,'50%','100%','150%','200%'))
答案 3 :(得分:0)
这是将事物保持在dplyr管道链中的解决方案。您预先对数据进行排序,然后使用mutate_at转换为因子。鉴于可以合理地排序数据,我对数据进行了一些修改,以显示该解决方案的一般应用范围:
# the data
temp <- data.frame(type=rep(c("T", "F", "P"), 4),
size=rep(c("50%", "100%", "200%", "150%"), each=3), # cannot sort this
size_num = rep(c(.5, 1, 2, 1.5), each=3), # can sort this
amount=c(48.4, 48.1, 46.8,
25.9, 26.0, 24.9,
20.8, 21.5, 16.5,
21.1, 21.4, 20.1))
temp %>%
arrange(size_num) %>% # sort
mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>% # convert to factor
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)
尽管您只能选择一个首选顺序,但您也可以应用此解决方案在小平面内排列条形图:
temp %>%
arrange(size_num) %>%
mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>%
arrange(desc(amount)) %>%
mutate_at(vars(type), funs(factor(., levels=unique(.)))) %>%
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)
ggplot() +
geom_bar(aes(x = type, y=amount, fill=type),
position="dodge", stat="identity") +
facet_grid(~ size)