R barplot incorrect color fill

Viewed 40

I am performing a simulation that involves taking sums of random numbers. For my barplot, I want to fill a winning number(numbers 7, 11, 21) as red, and the rest of the numbers as white. The color column in my data frame accurately assigns values a color, but when I produce a barplot, the colors are showing up incorrectly. What do I need to change?

    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"));
1 Answers

It looks like you need a new 'col' vector that has the same number of values as the prop.table output, i.e.

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"))

example.png

Does that make sense?

Related