【问题标题】:R barplot incorrect color fillR barplot不正确的颜色填充
【发布时间】:2021-02-22 22:23:46
【问题描述】:

我正在执行一个涉及对随机数求和的模拟。对于我的条形图,我想将中奖号码(数字 7、11、21)填充为红色,其余数字填充为白色。我的数据框中的颜色列准确地为值分配了颜色,但是当我生成条形图时,颜色显示不正确。我需要改变什么?

    set.seed(1);
    tickets = NULL;
    simNum = 500;
    for(i in 1:simNum){
        tickets = rbind(tickets, c(sum(box = sample(1:13, 3, replace = TRUE)), 
                         sum(box = sample(1:13, 3, replace = TRUE)), sum(box =  sample(1:13, 3, replace = TRUE))));
       }
    tickets = data.frame(tickets);

    #create data frame of all the sums 
    allSums = data.frame(c(tickets$sum1, tickets$sum2, tickets$sum3));
    allSums$col = "white";
    allSums$col[allSums[1] == 7 | allSums[1] == 11| allSums[1] == 21] = "red";
    barplot(prop.table(table(allSums[1])), col = as.vector(allSums$col));
    legend("right", legend = c("win", "lose"), fill = c("red", "white"));

【问题讨论】:

    标签: r graph statistics bar-chart


    【解决方案1】:

    看起来您需要一个新的“col”向量,它与 prop.table 输出具有相同数量的值,即

    set.seed(1);
    tickets = NULL;
    simNum = 5000;
    for(i in 1:simNum){
      tickets = rbind(tickets, c(sum(box = sample(1:13, 3, replace = TRUE)), 
                                 sum(box = sample(1:13, 3, replace = TRUE)), sum(box =  sample(1:13, 3, replace = TRUE))));
    }
    tickets = data.frame(tickets);
    names(tickets) =c("sum1", "sum2", "sum3");
    
    
    #create data frame of all the sums 
    allSums = data.frame(c(tickets$sum1, tickets$sum2, tickets$sum3))
    
    num_of_cols_in_proptable <- names(prop.table(table(allSums[1])))
    colors_for_proptable <- ifelse(num_of_cols_in_proptable %in% c(7, 11, 21), "red", "white")
    
    barplot(prop.table(table(allSums[1])), col = colors_for_proptable)
    legend("right", legend = c("win", "lose"), fill = c("red", "white"))
    

    这有意义吗?

    【讨论】:

    • 你打败了我!正确 - OP 当前使用两个参数调用 barplot()heightcol,同时将长度为 37 的数字向量输入到 height,将长度为 5000 的向量输入到 col
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2022-01-06
    • 2020-10-03
    相关资源
    最近更新 更多