我制作了某种“金字塔图”或“背对背图”来比较两组并检查每组中特定事件的比例(在本例中为某些药物的施用)。 感谢
ggh4x
软件包使我能够镜像体重秤,我已经完成了 90%。这是我用来生成下面第一个图的代码:
library(ggplot2)
library(ggh4x)
data <- data.frame(group = c("Group 1", "Group 1", "Group 2", "Group 2", "Group 1", "Group 1", "Group 2", "Group 2", "Group 1", "Group 1", "Group 2", "Group 2"),
administered = c("no", "yes", "no", "yes", "no", "yes", "no", "yes", "no", "yes", "no", "yes"),
medication = c("DRUG A with a long name", "DRUG A with a long name", "DRUG A with a long name", "DRUG A with a long name", "DRUG B", "DRUG B", "DRUG B", "DRUG B", "DRUG C", "DRUG C", "DRUG C", "DRUG C"),
count = c(100,200,50,88,99,300,77,45,12,0,9,27))
ggplot(data, aes(x = medication,
y = count,
fill = administered)) +
geom_col(position = "fill") +
ylab("proportion") +
scale_fill_manual(values = c("no"="#FF0000FF",
"yes"="#0000FFFF"))+
theme(axis.ticks.y = element_blank()) +
facet_wrap2(~ group, scales = "free") +
facetted_pos_scales(y = list(
scale_y_reverse(labels = scales::percent),
scale_y_continuous(labels = scales::percent))) +
coord_flip()
我想去掉第一个方面的标签,并将标签放在第一个和第二个方面之间的中心。我想要的结果是这样的:
非常感谢您的帮助!
这也可以通过
ggh2x
来实现。首先请注意,我切换了 x
和 y
aes 以摆脱 coord_flip
。与 x 轴一样,您也可以为每个面指定 y 轴,并将第一个面的轴放置在右侧。之后,您可以通过 theme
选项删除右侧的 y 比例。要将轴文本居中,请使用 hjust=.5
作为左侧 y 刻度,并如 @YoannPageaud 在评论中指出的那样,通过将左侧/右侧的边距设置为相同的量并删除面板之间的间距:
library(ggplot2)
library(ggh4x)
ggplot(data, aes(
y = medication,
x = count,
fill = administered
)) +
geom_col(position = "fill") +
labs(x = "proportion") +
scale_fill_manual(values = c(
"no" = "#FF0000FF",
"yes" = "#0000FFFF"
)) +
facet_wrap2(~group, scales = "free") +
facetted_pos_scales(
x = list(
scale_x_reverse(labels = scales::percent),
scale_x_continuous(labels = scales::percent)
),
y = list(
scale_y_discrete(position = "right"),
scale_y_discrete()
)
) +
theme(
axis.ticks.x = element_blank(),
axis.text.y.right = element_blank(),
axis.line.y.right = element_blank(),
axis.text.y.left = element_text(
hjust = .5,
margin = margin(l = 5.5, r = 5.5)
),
panel.spacing.x = unit(0, "pt")
)