我有一個按治療狀態和分類變數劃分的資料框組df %>% group_by(treatment, categorical_var) %>% summarise(n=n()),我正在嘗試使用 ggplot 獲得與圖片中顯示的類似的條形圖,其中我的 y 軸將由我的 $n$ 變數確定,而我的 x 軸將由我的 $categorical_var$ 決定

如圖所示,我基本上是在嘗試合并同一圖中的兩個條形圖,一個用于對照組,另一個用于治療組。有關如何執行此操作的任何幫助?
這是一個可重現的例子
example <- tribble(
~treatment, ~categorical_var, ~n,
"control", "1", 10,
"control", "2", 12,
"control", "3", 7,
"treatment", "1", 14,
"treatment", "2", 5,
"treatment", "3", 11,
)
ggplot(example, aes(categorical_var, n))
geom_bar(position="dodge",stat="identity") facet_wrap(~treatment)
這是我得到的 putput,我如何更改樣式以從上面獲得類似圖片的內容?

uj5u.com熱心網友回復:
造型總是涉及一些擺弄和試驗(有時會出錯(;)。但通常你可能會非常接近你想要的結果,如下所示:
library(ggplot2)
ggplot(example, aes(categorical_var, n))
geom_bar(position="dodge",stat="identity")
# Add some more space between groups
scale_x_discrete(expand = expansion(add = .9))
# Make axis start at zero
scale_y_continuous(expand = expansion(mult = c(0, .05)))
# Put facet label to bottom
facet_wrap(~treatment, strip.position = "bottom")
theme_minimal()
# Styling via various theme options
theme(panel.spacing.x = unit(0, "pt"),
strip.placement = "outside",
strip.background.x = element_blank(),
axis.line.x = element_line(size = .1),
panel.grid.major.y = element_line(linetype = "dotted"),
panel.grid.major.x = element_blank(),
panel.grid.minor = element_blank())

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/376598.html
上一篇:對齊圖例水平ggplot2
