r - 在ggplot2中的x轴上绘制有序因子
问题描述
我有以下数据。
pos <- c(1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,4,5,6)
block <- c(1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2)
set <- c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4)
fsize <- c(4,5,6,1,2,1,2,2,3,4,5,1,7,11,2,1,2,3,5,3,5,6,1,2)
dat <- data.frame(pos,block,set,fsize)
dat <- dat[order(block,set,-fsize),]
dat$pos <- as.factor(dat$pos)
ggplot(dat, aes(x = pos, y = fsize)) + geom_bar(stat="identity") +
facet_wrap(~block+set)
每个位置pos
都与一个 size 相关联fsize
。每个块/组内有 6 个位置。我想以减少女性尺寸的方式排列尺寸。因此,例如,具有重新排列位置的第一个块/集将是3,2,1,5,4,6
,而另一个块/集将是不同的。但是,当我绘制它时,即使我考虑pos
列,x 轴也会自动重新排序为 1-6。有关如何纠正此问题的任何建议?
解决方案
这是一个解决方案,但为了按所需顺序绘制,我需要创建一个具有唯一名称的新变量。变量是set
和pos
列的组合。
dat <- data.frame(pos,block,set,fsize)
dat <- dat[order(block,set,-fsize),]
#make a key variable in the overall desired order
key<-paste(dat$set, dat$pos, sep=",")
#make an new ordered factor variable in the proper order
dat$order <- factor(key, levels= key, ordered =TRUE)
ggplot(dat, aes(x = order, y = fsize)) + geom_bar(stat="identity") +
facet_wrap(~block+set, scales="free_x") + labs(x="Set,Pos")
推荐阅读
- python - Python 如何销毁垃圾?
- c# - 如何使用异步技巧在 C# 中处理 IO 和 CPU 混合绑定任务?
- corda - build\nodes\runnodes 有问题
- javascript - 如何循环遍历 div?
- azure - 如何在 .net core 3.1 中使用 log4net 将日志保存在 blob 文本文件中
- xaml - Xamarin DataGrid 标题垂直向下
- c# - 保护内存中的对称加密密钥
- c# - IAsyncEnumerable 不包含 ADO.NET 中“GetAwaiter”的定义
- html - 授权函数的thymeleaf语法
- jmeter - 事务控制器中的实际失败消息(如果它由多个采样器组成)