如何在ggmosaic中翻转马赛克图?例如,我想要这样:
看起来像这样:
请注意,“ present”在第一张图的顶部和第二张图的底部。我想在第一个情节的底部做一个“礼物”。
数据是HSAUR3软件包中的“精神分裂症2”数据集。这是代码:
#import the data set
data("schizophrenia2", package="HSAUR3")
#plot in base R
library(vcd)
colors <- c("grey", "darkred")
mosaic(disorder ~ month | onset, highlighting_fill = colors, data = schizophrenia2, main = "Presence of Thought Disorder by Onset of Disease")
#plot in ggplot2
library(ggmosaic)
ggplot(data = schizophrenia2) +
geom_mosaic(aes(x = product(month, onset), fill=disorder), na.rm=T) +
labs(title="Presence of Thought Disorder by Onset of Disease", x="Onset", y="Month") +
coord_flip() +
scale_fill_discrete(guide = guide_legend(reverse=TRUE),
name="Disorder", labels=c("Absent", "Present", "Dropped Out"))
注意:加载ggmosaic时,VCD可能会停止工作。它是在我的。但是我想我只是在ggmosaic中缺少一些简单的代码,可以让我翻转它。
答案 0 :(得分:0)
如果有人感兴趣,我会使用tidyverse包以相反的顺序通过管道传递数据
答案 1 :(得分:0)
问题在于变量的级别在ggplot2对象中的映射顺序。您可以通过对onset
和disorder
变量重新排序来获得所需的结果。
#import the data set
data("schizophrenia2", package="HSAUR3")
#plot in ggplot2
library(ggmosaic)
library(dplyr)
schizophrenia2 %>%
mutate(onset = forcats::fct_relevel(onset, "> 20 yrs"),
disorder = forcats::fct_relevel(disorder, "present")) %>%
ggplot() +
geom_mosaic(aes(x = product(month, onset), fill=disorder), na.rm=T) +
labs(title="Presence of Thought Disorder by Onset of Disease") +
scale_x_productlist(name="Onset") +
scale_y_productlist(name="Month") +
coord_flip() +
scale_fill_discrete(guide = guide_legend(reverse=TRUE),
name="Disorder", labels=c("Present", "Absent", "Dropped Out"))