R语言 在ggplot2中应用自定义模型标签

khbbv19g  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(129)

这可能是微不足道的,但我如何:
1.将标签应用于y轴上的每个modelnum值?可以将“a”命名为“Label1”,将“b”命名为“Label2”或类似的名称。
1.在每个面内颠倒顺序,使字母表中较高的字母位于给定面的顶部?
代码:

library(ggplot2)
ggplot(d, aes(y = modelnum, x = odds_ratio, color = sample,
               xmin = ci_lower, xmax = ci_upper)) +
  geom_errorbar(width = .1) +
  geom_point(size = 3) +
  geom_vline(xintercept = 1, 
             linetype = "dashed", 
             color = "black",
             linewidth = .3) +
  facet_wrap(~sample,
             scales = "free_y",
             nrow = 3) +
  scale_color_manual(values = c("Never" = "gray30",
                                "Pooled" = "red",
                                "Post" = "blue")) +
  labs(title = "Models",
       x = "Odds Ratio",
       y = "") +
  theme_bw() +
  theme(legend.position = "none"
        )

字符串
数据类型:

d <- structure(list(modelnum = c("a", "b", "c", "a", "b", "d", "e", 
"f"), odds_ratio = c(0.11, 0.151, 0.0629, 0.193, 0.052, 0.1065, 
0.2, 0.089), ci_lower = c(0.048, 0.054, 0.0049, 0.052, 0.004, 
0.0566, 0.067, 0.017), ci_upper = c(0.271, 0.425, 0.799, 0.646, 
0.72, 0.19, 0.5948, 0.461), sample = c("Pooled", "Pooled", "Pooled", 
"Never", "Never", "Never", "Post", 
"Post")), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -8L))

am46iovg

am46iovg1#

你可以像Map颜色一样做这件事,只需要在ggplot中的某个地方添加这个:

+ scale_y_discrete(labels = c("a"="Label1", "b"="Label2"), limits=rev)

字符串
limits=rev选项将反转离散轴。您也可以使用数值并将中断/标签Map到那些更细粒度的顺序控制。

s3fp2yjn

s3fp2yjn2#

创建一个label变量,并相应地在aes()中重新排序y,即y = reorder(label, desc(modelnum))

library(ggplot2); library(dplyr)
d |>
  mutate(label = paste0("Label", modelnum)) |>
  ggplot(aes(y = reorder(label, desc(modelnum)), x = odds_ratio, color = sample,
              xmin = ci_lower, xmax = ci_upper)) +
  geom_errorbar(width = .1) +
  geom_point(size = 3) +
  geom_vline(xintercept = 1, 
             linetype = "dashed", 
             color = "black",
             linewidth = .3) +
  facet_wrap(~ sample,
             scales = "free_y",
             nrow = 3) +
  scale_color_manual(values = c("Never" = "gray30",
                                "Pooled" = "red",
                                "Post" = "blue")) +
  labs(title = "Models",
       x = "Odds Ratio",
       y = "") +
  theme_bw() +
  theme(legend.position = "none")

字符串

相关问题