首页 文章

另一列分组的条形图

提问于
浏览
0

这可能是之前被问过,但找不到搜索 .

我正试图在我的数据集“栖息地”中描绘一个名为“pet”的变量,这个变量分为3类 - “Y”,“N”,“Null” .

以下代码有效:

>barplot(table(habitat$pet),main = "Pet Distribution", 
  xlab = "Pet categories", ylab = "count", col = c("darkblue"))

现在我有另一个名为“结果”的二进制列 . 按结果划分频率的分组条形图是否容易?

我正在尝试跟随,这是行不通的:

>counts = table(habitat$pet[habitat$outcome == 0],habitat$pet[habitat$outcome == 1])
>barplot(counts,main = "Pet Distribution by Outcome", xlab = "Pet categories", 
    ylab = "count", col = c("darkblue","red"), beside = TRUE)

错误在“计数”部分,因为参数的长度不同 . 还有其他方法吗?

数据如下:

ID   pet  outcome   
1     Y     1          
2     N     1
3     N     0
4     Y     0
...

2 回答

  • 1

    你可以做这样的事情 . 我正在生成一些示例数据,因为您的示例数据似乎没有代表性(例如,您没有“NULL”条目) .

    # Generate sample data
    set.seed(2017);
    df <- data.frame(
        ID = 1:100,
        pet = sample(c("N", "Y", "NULL"), 100, prob = c(0.1, 0.8, 0.2), replace = T),
        outcome = sample(c(0, 1), 100, replace = T))
    
    # Plot
    ggplot(df, aes(pet)) + geom_bar()
    

    enter image description here

  • 0

    我不确定我得到了你想要的东西,但尝试以下代码:

    if(!require(ggplot2)){install.packages('ggplot2')
    library(ggplot2)
    ggplot(data = habitat, aes(x = pet)) +
     geom_bar(position = 'fill', aes(fill = outcome)) +
     labs(x = 'Pet Categories', title = 'Pet Distribution by Outcome') +
     scale_fill_manual(values = c('darkblue','red'))
    

    如果您没有寻求按比例堆叠的条形图,请跳过 position 参数 .

相关问题