带有条件的R Grouped Bar Plots

问题描述 投票:0回答:1

我试图比较两个变量,并根据它们的相关性创建一个分组条形图。流失列是“是”或“否”。 “合同”列可以是“按月”,“一年”或“两年”。我最终想要的是一个分组条形图,其中包含每种合同类型的Yeses和Nos总数。例如,每月合约类型在Churn列中有2220个Nos和1655个Yeses。

我必须将Churn与其他两个类似性质的列进行比较,所以起初我试图创建一个循环通过每列的级别的函数,拉出信息,然后将其转储到向量中,然后开始读取附加到向量的列R的循环不是最佳实践。

所以我对此采取了很长的路要走:

contractLevels = levels(cd$Contract)
c1n = length(cd$Contract[which(cd$Churn == "No" & cd$Contract == contractLevels[1])])
c1y = length(cd$Contract[which(cd$Churn == "Yes" & cd$Contract == contractLevels[1])])
c2n = length(cd$Contract[which(cd$Churn == "No" & cd$Contract == contractLevels[2])])
c2y = length(cd$Contract[which(cd$Churn == "Yes" & cd$Contract == contractLevels[2])])
c3n = length(cd$Contract[which(cd$Churn == "No" & cd$Contract == contractLevels[3])])
c3y = length(cd$Contract[which(cd$Churn == "Yes" & cd$Contract == contractLevels[3])])
cv <- c(c1n, c1y, c2n, c2y, c3n, c3y)
cv
cn <- c(paste(contractLevels[1], "No"), paste(contractLevels[1], "Yes"), paste(contractLevels[2], "No"), paste(contractLevels[2], "Yes"), paste(contractLevels[3], "No"), paste(contractLevels[3], "Yes"))

我仍然希望尽可能简单地重用,所以我没有输入实际的新列名(cn)。首先,必须有一种更简单的方法来做上面的事情,而且我只是太过一个R noobie来解决它。其次,我无法将其作为带有此数据的分组条形图。我试图遵循这个:http://www.r-graph-gallery.com/48-grouped-barplot-with-ggplot2/但由于cn和cv向量没有7032“行”(就像我的数据一样),它不起作用。

是否可以这样说:图表列Y中每个级别的列X在“Y”列中表示“是”的总次数,除了在Y列中为每个级别显示“否”的总次数。我一直在玩rpart,plot和ggplot试图解决这个问题。

只是做plot(cd$Contract, cd$Churn)给了我一个堆叠的图形,这是我想要的,除了有点难以阅读。做barplot(cv, ylab="Churn", names.arg=cn, cex.names=0.5, las=2)给了我没有分组的条形图,也有点难以阅读。 Stacked Graph

Barchart

r plot ggplot2
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.