ggplot facet_wrap 每个方面都有特定的变量顺序
ggplot facet_wrap with specific order of variables in each facet
我想用 ggplot 绘制这些数据:
library(ggplot2)
set.seed(0)
df <- data.frame(
var1 = rep(c("group1", "group2"), each = 3),
var2 = rep(letters[1:3], 2),
value = runif(6, 0, 10)
)
情节应该是这样的:
pl <- ggplot(df, aes(var2, value))
pl <- pl + geom_col()
pl <- pl + facet_wrap(~ var1, scales = "free")
pl
var2
在x轴上的顺序应该由value
的递增顺序决定。我可以做到这一点:
df$temp_var <- paste(df$var1, df$var2)
pl <- ggplot(df, aes(reorder(temp_var, value), value))
pl <- pl + geom_col()
pl <- pl + facet_wrap(~ var1, scales = "free")
pl
但是,x 轴标签应为 a
、b
和 c
。通常,我会将 var2
转换为因子水平具有我想要的顺序的因子,但在这种情况下,这可能是不可能的。
有人知道如何做到这一点吗? :)
只需将轴标签设置为不同于使用命名字符向量的实际中断:
pl + scale_x_discrete(labels = setNames(as.character(df$var2), df$temp_var))
我想用 ggplot 绘制这些数据:
library(ggplot2)
set.seed(0)
df <- data.frame(
var1 = rep(c("group1", "group2"), each = 3),
var2 = rep(letters[1:3], 2),
value = runif(6, 0, 10)
)
情节应该是这样的:
pl <- ggplot(df, aes(var2, value))
pl <- pl + geom_col()
pl <- pl + facet_wrap(~ var1, scales = "free")
pl
var2
在x轴上的顺序应该由value
的递增顺序决定。我可以做到这一点:
df$temp_var <- paste(df$var1, df$var2)
pl <- ggplot(df, aes(reorder(temp_var, value), value))
pl <- pl + geom_col()
pl <- pl + facet_wrap(~ var1, scales = "free")
pl
但是,x 轴标签应为 a
、b
和 c
。通常,我会将 var2
转换为因子水平具有我想要的顺序的因子,但在这种情况下,这可能是不可能的。
有人知道如何做到这一点吗? :)
只需将轴标签设置为不同于使用命名字符向量的实际中断:
pl + scale_x_discrete(labels = setNames(as.character(df$var2), df$temp_var))