[英]Order geom_bar groups
我有这个数据:
country name value
<chr> <chr> <dbl>
1 Germany Jd 7.1
2 Germany Jc 8.4
3 Germany Ne 1.3
4 France Jd 8.3
5 France Jc 12
6 France Ne 3.7
我想将 plot 分成两组(每组三列)。 与 dataframe 中的顺序相同:第一德国,第二法国以及 Jd、Jc、Ne 列的顺序。
我做了:
p <- ggplot(data, aes(x = country, y = value)) +
geom_bar(aes(fill = name), width=0.7, position = position_dodge(width=0.7), stat='identity')
但我得到 plot 的顺序不同:首先是法国,然后是德国,以及列 Jc、Jd、Ne 的顺序。 (似乎按字母顺序排列)。
我怎样才能以我想要的方式订购酒吧?
可能控制排序的最简单方法之一是将as.factor()
转换为您的排序列并定义级别,您将覆盖任何其他默认排序:
library(ggplot2)
data$country <- factor( data$country, levels = c("Germany", "France"))
data$name <- factor( data$name, levels = c("Jd", "Jc", "Ne"))
ggplot(data, aes(x = country, y = value,fill = name)) +
# moved the aes() all together, nothing related to the question
geom_bar(width=0.7, position position_dodge(width=0.7), stat='identity')
有data
:
data <- read.table(text = "
country name value
Germany Jd 7.1
Germany Jc 8.4
Germany Ne 1.3
France Jd 8.3
France Jc 12
France Ne 3.7",header = T)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.