我在 R 中有一个名为 df 的数据框:
set.seed(123) # Setting seed for reproducibility
levels <- c('a', 'b', 'c', 'd', 'e')
my_var <- sample(levels, 50, replace = TRUE)
levels2 <- c('a', 'b', 'c', 'd', 'e','f','h')
my_var2 <- sample(levels2, 50, replace = TRUE)
delta <- rnorm(50, mean = 0, sd = 1)
df = tibble(my_var,my_var2,delta);df
# A tibble: 50 × 3
my_var my_var2 delta
<chr> <chr> <dbl>
1 c h 0.304
2 c a 0.448
3 b h 0.0530
4 b b 0.922
5 c d 2.05
6 e h -0.491
7 d d -2.31
8 a f 1.01
9 b f -0.709
10 c c -0.688
# ℹ 40 more rows
我想用像我附加的图片这样的方面来绘制它们,但增量列的值要从最差到最好排序。(即从较小到较大),但从每个方面的底部和左侧开始最差并增加到最好(更大)在右上角。
我怎样才能实现这个目标?
df = tibble(my_var,my_var2,delta);df
df%>%
mutate(BandRange = factor(my_var2,levels=levels2)) %>%
ggplot(aes(x = delta, y = (my_var2), color = "black")) +
geom_point(size = 3) +
facet_grid(my_var ~., scales="free") +
labs(y="my_var2") +
geom_vline(xintercept=0) +
theme_bw() +
theme(legend.position = "none", # Remove the legend
axis.text.x = element_text(angle = 0 , hjust = 1), # Rotate x-axis labels
strip.text.y = element_text(size = 8 , angle = 0, vjust = 0.5),
axis.text.y = element_text(size = 7),
strip.text = element_text(size = 14), # Increase facet label size
axis.title = element_text(size = 14), # Increase axis title size
axis.text = element_text(size = 10))+ # Increase axis text size
theme(strip.background = element_rect(color="black", size=1.5, linetype="solid"))+
labs(title = "",x = "")
您需要将分面变量变成有序因子,并根据 x 轴变量的平均值对级别进行排序。您可以使用
forcats::fct_reorder()
来完成此操作。这是一个可重现的示例:
library(forcats)
library(ggplot2)
## Creating example data ------------------------------------------------
rands <- function() runif(100, 100, 300)
lo <- rands() - 100
mid <- rands()
hi <- rands() + 100
df <- data.frame(set = rep(c("lo", "hi", "mid"), each = 100),
nums = c(lo, hi, mid),
y = rnorm(300))
## Make `set` ordered, then reorder by `nums` using fct_reorder() ------
### .desc = TRUE reverses the order, putting lower values at the
### bottom of the plot
df$set <-
ordered(df$set) |>
fct_reorder(df$nums, .desc = TRUE)
## Plot -----------------------------------------------------------------
ggplot(df, aes(x = nums, y = y)) +
geom_point() +
facet_wrap(~ set, dir = "v")
创建于 2024-11-06,使用 reprex v2.1.1