簡體   English   中英

在RStudio上以圖表顯示交叉列表

[英]Displaying a Cross-tabulation As a Plot on RStudio

我正在嘗試使用ggplot2可視化RStudio上的交叉列表。 我過去可以創建圖,也可以完成交叉列表,但是無法破解。 有人可以幫忙嗎?

這是我的x標簽的代碼:

library(dplyr)
data_dan %>%
  group_by(Sex, Segment) %>%
  count(variant) %>%
  mutate(prop = prop.table(n))

這是創建情節所需要的:

#doing a plot
variance_art_new.plot = ggplot(data_dan,  aes(Segment, fill=variant)) +
  geom_bar(position="fill")+
  theme_classic()+
  scale_fill_manual(values = c("#fc8d59", "#ffffbf", "#99d594"))
variance_art_new.plot

這是我正在處理的數據的示例:

   Word  Segment  variant  Position     Sex
1  LIKE       K       R       End      Female
2  LITE       T       S       End      Male
3 CRACK       K       R       End      Female
4  LIKE       K       R       End      Male
5  LIPE       P       G       End      Female
6  WALK       K       G       End      Female

我的目標是在箱形圖上針對因變量“ variant”繪制自變量“ Sex”,“ Segment”。 我包括了第一個代碼,以表明我可以創建一個表來顯示此交叉表,第二個代碼是我通常只為一個自變量運行箱形圖時要做的事情。

我仍然不確定這是否完全符合您的要求,但是如果您要在兩個單獨的變量中要求計數(或份數),則可以使用facet_wrap來分隔這兩個組。

(請注意,所有這些都與theme_set(theme_bw())一起運行,因為我更喜歡在這種情節中使用它。)

使用內置數據集mtcars您可以使用以下方法獲得計數:

mtcars %>%
  ggplot(aes(x = factor(cyl), fill = factor(gear))) +
  geom_bar() +
  facet_wrap(~vs)

在此處輸入圖片說明

或將排序反向:

mtcars %>%
  ggplot(aes(x = factor(vs), fill = factor(gear))) +
  geom_bar() +
  facet_wrap(~cyl, labeller = label_both)

在此處輸入圖片說明

您還可以使用position = "fill"繪制組內分布

mtcars %>%
  ggplot(aes(x = factor(vs), fill = factor(gear))) +
  geom_bar(position = "fill") +
  facet_wrap(~cyl, labeller = label_both) +
  scale_y_continuous(name = "Within group Percentage"
                     , labels = scales::percent)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM