R 在ggplot2中按升序绘制由另一个变量分组的变量的级别

R 在ggplot2中按升序绘制由另一个变量分组的变量的级别,r,ggplot2,R,Ggplot2,我想按变量的级别按升序排列条形图。其他的职位和不工作 下面是一个示例数据 x <- c(rep(letters[1:2], each = 6)) y <- c(rep(letters[3:8], times = 2)) z <- c(2, 4, 7, 5, 11, 8, 9, 2, 3, 4, 10, 11) dat <- data.frame(x,y,z) 然而,结果图并不是我所期望的 ggplot(dat2, aes(y,z)) + geom_bar(stat

我想按变量的级别按升序排列条形图。其他的职位和不工作

下面是一个示例数据

x <- c(rep(letters[1:2], each = 6))
y <- c(rep(letters[3:8], times = 2))
z <- c(2, 4, 7, 5, 11, 8, 9, 2, 3, 4, 10, 11)
dat <- data.frame(x,y,z)
然而,结果图并不是我所期望的

ggplot(dat2, aes(y,z)) +
  geom_bar(stat = "identity") +
  facet_wrap(~x, scales = "free")

如何将
y
的级别按
z
的递增顺序排列
x

如果您希望条形图在每个面内递增,则相同的
y
值需要在不同面的不同位置。请尝试以下方法:

dat3 <- dat %>%
  mutate(x.y = paste(x, y, sep = ".")) %>%
  mutate(x.y = factor(x.y, levels = x.y[order(z)]))
# this creates a new variable that combines x & y; different facets
# simply use different subsets of values from this variable

ggplot(dat3, aes(x.y,z)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(name = "y", breaks = dat3$x.y, labels = dat3$y) +
  facet_wrap(~x, scales = "free")
dat3%
突变(x.y=粘贴(x,y,sep=“.”)%>%
突变(x.y=因子(x.y,级别=x.y[顺序(z)])
#这将创建一个结合x&y;不同方面
#只需使用此变量的不同值子集即可
ggplot(dat3,aes(x.y,z))+
几何图形栏(stat=“identity”)+
比例x离散(name=“y”,分段=dat3$x.y,标签=dat3$y)+
面_包裹(~x,scales=“自由”)

哇。现在我明白了,这很有道理。这么巧妙的把戏。非常感谢。
dat3 <- dat %>%
  mutate(x.y = paste(x, y, sep = ".")) %>%
  mutate(x.y = factor(x.y, levels = x.y[order(z)]))
# this creates a new variable that combines x & y; different facets
# simply use different subsets of values from this variable

ggplot(dat3, aes(x.y,z)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(name = "y", breaks = dat3$x.y, labels = dat3$y) +
  facet_wrap(~x, scales = "free")