【问题标题】:How can I flip a mosaic plot in ggmosaic?如何在 ggmosaic 中翻转马赛克图?
【发布时间】:2019-03-30 18:23:27
【问题描述】:

如何在 ggmosaic 中翻转马赛克图?例如,我想要这个:

看起来像这样:

注意“present”在第一个图中位于顶部,在第二个图中位于底部。我想在第一个情节的底部制作“礼物”。

数据是 HSAUR3 包中的“schizophrenia2”数据集。代码如下:

#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 中遗漏了一些简单的代码,可以让我翻转它。

【问题讨论】:

标签: r ggmosaic


【解决方案1】:

问题是变量的级别在 ggplot2 对象中映射的顺序。您可以通过重新排序 onsetdisorder 变量来获得所需的结果。

#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"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-13
    • 2018-01-03
    • 2017-09-23
    • 1970-01-01
    • 2020-07-07
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多