我正在使用 ggplot 使用
facet_grid()
绘制三个图。绘图和图例的默认顺序是按字母顺序排列的。为了调整顺序,我考虑了相关变量并确认设定了预期水平。然而,这些图仍然按字母顺序显示。因式分解确实调整了图例和颜色分配中的样本顺序,但没有调整绘图的顺序。
我发现许多解决方案在绘图创建中添加了因素,但我想事先考虑我的数据,以便绘图代码尽可能简单。
谁能解释为什么我的因式分解方法不适用于分面的情节安排?有没有一种简单的方法可以在创建绘图之前添加因子级别,
facet_grid()
会遵守?
library(tidyverse)
Sample_Table <- data.frame(
Sample=c(1:9),
Group=c("B", "B", "B", "A", "A", "A", "C", "C", "C"))
data <- data.frame(
Position=c(rep(1:5000,times=3)),
Signal=c(rep(0,times=2000), rep(25,times=1000), rep(0,times=2000),
rep(0,times=2000), rep(50,times=1000), rep(0,times=2000),
rep(0,times=2000), rep(75,times=1000), rep(0,times=2000)),
Group=c(rep("A", times=5000), rep("B", times=5000), rep("C", times=5000))
)
data_factor <- data %>%
dplyr::mutate(Group = factor(Group, levels=c(paste0(unique(Sample_Table$Group)))))
colorscale <- c("#ffe119", "#f58231", "#9A6324")
Plot <- ggplot(data) +
geom_line(aes(x=Position, y=Signal, col=Group), linewidth=.4) +
scale_color_manual(values=c(colorscale)) +
facet_grid(paste0(Group)~.) +
theme_bw() +
theme(axis.text.x = element_blank()) +
theme(
axis.title.x = element_text(margin=margin(t=30)),
legend.title = element_text(colour = "#333333", size=12),
legend.text = element_text(colour = "#333333", size=12)
) +
guides(fill = "none")
Plot_Factored <- ggplot(data_factor) +
geom_line(aes(x=Position, y=Signal, col=Group), linewidth=.4) +
scale_color_manual(values=c(colorscale)) +
facet_grid(paste0(Group)~.) +
theme_bw() +
theme(axis.text.x = element_blank()) +
theme(
axis.title.x = element_text(margin=margin(t=30)),
legend.title = element_text(colour = "#333333", size=12),
legend.text = element_text(colour = "#333333", size=12)
) +
guides(fill = "none")
library(ggh4x)
library(ggplot2)
library(dplyr)
data %>%
mutate(Group = factor(Group, levels=c(paste0(unique(Sample_Table$Group))))) %>%
ggplot() +
geom_line(aes(x=Position, y=Signal, col=Group), linewidth=.4)+
scale_color_manual(values=c(colorscale)) +
facet_grid(Group~.) +
theme_bw() +
theme(axis.text.x = element_blank()) +
theme(
axis.title.x = element_text(margin=margin(t=30)),
legend.title = element_text(colour = "#333333", size=12),
legend.text = element_text(colour = "#333333", size=12)
) +
guides(fill = "none")