r - 订购 geom_bar 组
问题描述
我有这个数据:
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
我想将它绘制成两组条形图(每组三列)。与数据框中的顺序相同:第一个德国,第二个法国以及 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')
但我以不同的顺序得到情节:首先是法国,然后是德国,以及列 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)
推荐阅读
- ios - 下载时如何处理睡眠后iOS应用程序崩溃?
- java - 获取远程服务器文件夹中的图像路径
- python - 迭代日期时间对象?
- python - python中有没有办法判断变量是否是系统命令
- javascript - 如何使用 javascript 代码删除/修剪 .xml 标记
- python - 保存来自 Tello Drone 的视频
- ruby-on-rails - 如何使用rails在括号中搜索确切的单词?
- jquery - 多个ajax请求
- selenium-webdriver - 运行负载测试时 Java 运行时环境的内存不足
- json - 当我们在 golang 中将空 Json 解组为 struct 时会发生什么?