绘制3个分类变量,依赖于前一列

时间:2018-03-01 05:44:58

标签: r ggplot2 categorical-data

我想要使用r(ggplot2或任何其他包)绘制以下数据

问题是:在R中进行可视化的最佳方法是什么,以了解Happy = Yes,Pay = No和Donate = Yes(以及其他组合)之间的关系。

AreYouHappy | WouldYouPay | WouldYouDonate

Yes | No  | Yes

Yes | No  | No

Yes | No  | Yes

Yes | Yes | Yes

Yes | No  | No

No  | Yes | Yes

Yes | No  | No

Yes | No  | Yes

...[58 data points]

[可重复代码]

df <- data.frame(
  cbind(AreYouHappy = sample( c("Yes", "No"), 58, replace = TRUE, prob = c(.75,.25)),
        WouldYouPay = sample( c("Yes", "No"), 58, replace = TRUE, prob = c(.25,.75)),
        WouldYouDonate = sample( c("Yes", "No"), 58, replace = TRUE, prob = c(.50,.50))))

我尝试了VennDiagram,SankeyDiagram,Bar,Mosiac Plot,使用ggplot2 / plotluck但是我无法处理它们中的任何一个。我尝试过使用reshape2,但我无法理解如何将这些数据点更改为计数矩阵然后绘制它。我搜索了一遍。请帮忙 - 我哪里错了?

2 个答案:

答案 0 :(得分:3)

如果它有关幸福的数据集那么为什么不使用upset: - )

# Data
df <- data.frame( cbind(AreYouHappy = sample( c("Yes", "No"), 58, replace = TRUE, prob = c(.75,.25)), WouldYouPay = sample( c("Yes", "No"), 58, replace = TRUE, prob = c(.25,.75)), WouldYouDonate = sample( c("Yes", "No"), 58, replace = TRUE, prob = c(.50,.50))))
# Transform original data into 0 and 1
df01 <- apply(df, 2, function(x) ifelse(x == "Yes", 1, 0))

# Plot using UpSetR
library(UpSetR)
upset(data.frame(df01))

enter image description here

有关UpSetR的更多信息in the vignette

答案 1 :(得分:0)

试试这个:

require(ggplot2)
ggplot(df, aes(WouldYouPay)) + geom_bar(aes(fill = WouldYouDonate)) +
   facet_wrap(~AreYouHappy, labeller = "label_both")