如何解决R barplot颜色填充不正确
我正在执行一个模拟,其中涉及对随机数求和。对于我的绘图,我想用红色填充一个中奖号码(数字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,sum(box = sample(1:13,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"));
解决方法
您似乎需要一个新的'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,sum(box = sample(1:13,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"))
这有意义吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。