我有一個使用 facet 的圖,如下所示:
library(tidyverse)
dat <- data.frame(grp = c("a", "a", "b", "b"),
ep = c("r1", "r2", "r1", "r2"),
val = c(3, 5, 2, 5),
suffix = c("_w", "_x", "_y", "_z"))
dat %>%
ggplot(aes(x = ep, y = val, fill = ep))
geom_col(position = "dodge")
facet_wrap(~grp)

我想將后綴列附加到每個 x 軸標簽,以便最終結果如下所示:

我在下面嘗試過這種方法,但它說找不到后綴變數:
dat %>%
ggplot(aes(x = ep, y = val, fill = ep))
geom_col(position = "dodge")
scale_x_discrete(labels = function(x) paste0(x, suffix))
facet_wrap(~grp)
uj5u.com熱心網友回復:
不要在ggplot里面做,先創建后綴列。
library(tidyverse)
dat <- data.frame(grp = c("a", "a", "b", "b"),
ep = c("r1", "r2", "r1", "r2"),
val = c(3, 5, 2, 5),
suffix = c("_w", "_x", "_y", "_z"))
dat %>%
mutate(x_suffix = paste0(ep, suffix)) %>%
ggplot(aes(x = x_suffix, y = val, fill = ep))
geom_col(position = "dodge")
facet_wrap(~grp, scales = "free_x")

由reprex 包(v2.0.1)于 2021 年 12 月 1 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/371924.html
