首页 > 解决方案 > 在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。有关如何纠正此问题的任何建议?

标签: rsortingggplot2

解决方案


这是一个解决方案,但为了按所需顺序绘制,我需要创建一个具有唯一名称的新变量。变量是setpos列的组合。

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")

在此处输入图像描述


推荐阅读