重新排列脊线图中的面板

时间:2020-02-17 07:11:53

标签: r ggplot2 ggridges ridgeline-plot

我有一个这样的数据框:

set.seed(3467)

 df<- data.frame(method= c(rep("A", 1000), rep("B", 1000), rep("C", 1000)), 
        beta=c(rnorm(1000, mean=0, sd=1),rnorm(1000, mean=2, sd=1.4),rnorm(1000, mean=0, sd=0.5)))

我希望创建类似于以下的山脊线图:

library(ggplot2)
library(ggridges)

ggplot() +
geom_rect(data = data.frame(x = 1),
        xmin = -0.391, xmax = 0.549, ymin = -Inf, ymax = Inf,
        alpha = 0.5, fill = "gray") +
 geom_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  size=0.75)+
 xlim(-5,5)+
 scale_fill_manual(values = c("#483d8b50", "#0072B250","#228b2250")) +
 scale_color_manual(values = c("#483d8b", "#0072B2", "#228b22"), guide = "none") +
 stat_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  quantile_lines = TRUE, quantiles = c(0.025, 0.5, 0.975), alpha = 0.6, size=0.75)+
scale_y_discrete(expand = expand_scale(add = c(0.1, 0.9)))

但是,我希望按method= "B", "C", "A"而不是method= "A", "B", "C"的顺序排列y轴

我尝试了以下方法,但没有成功,以重新排列密度图:

library(dplyr)
df %>%
 mutate(method = fct_relevel(method, 
                        "B", "C", "A"))%>%
ggplot() +
geom_rect(data = data.frame(x = 1),
        xmin = -0.391, xmax = 0.549, ymin = -Inf, ymax = Inf,
        alpha = 0.5, fill = "gray") +
 geom_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  size=0.75)+
 xlim(-5,5)+
 scale_fill_manual(values = c("#483d8b50", "#0072B250","#228b2250")) +
 scale_color_manual(values = c("#483d8b", "#0072B2", "#228b22"), guide = "none") +
 stat_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  quantile_lines = TRUE, quantiles = c(0.025, 0.5, 0.975), alpha = 0.6, size=0.75)+
scale_y_discrete(expand = expand_scale(add = c(0.1, 0.9)))

2 个答案:

答案 0 :(得分:2)

您快到了。 -您需要在levels中指定fct_relevel参数。 (请参阅?fct_relevel:没有levels参数,但是...,您必须指定其名称!)

library(tidyverse)
library(ggridges)
set.seed(3467)

df<- data.frame(method= c(rep("A", 1000), rep("B", 1000), rep("C", 1000)), 
                beta=c(rnorm(1000, mean=0, sd=1),rnorm(1000, mean=2, sd=1.4),rnorm(1000, mean=0, sd=0.5)))

# here is the main change: 
df <- df %>%
  mutate(method = fct_relevel(method, levels = "B", "C", "A"))

  ggplot(df) +
  geom_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method))
#> Picking joint bandwidth of 0.225

reprex package(v0.3.0)于2020-02-17创建

答案 1 :(得分:1)

如果将“方法”列更改为有序因子,则它应该起作用:

df$method <- factor(df$method, levels = c("C", "A", "B"), ordered = TRUE)