【发布时间】:2023-04-06 14:19:01
【问题描述】:
我在 R 中找到了以下代码,它绘制了一个直方图并将一些条形涂成红色:
n = floor(rnorm(10000, 500, 100))
t = table(n)
# get color counts
r <- floor(length(t)/2)
b <- length(t) - r
# repeat red r times, repeat black b times
barplot(t, col = rep(c("red", "black"), c(r, b)), border = NA)
# use "topleft" to place legend
legend("topleft", legend=c("group a", "group b"),
col=c("red", "black"), lty = 1, cex=0.8)
title(main = "some title",
sub = "some title")
如上代码所示,这要求数据为“表格”格式。
问题:我正在尝试制作相同的图表,但改用“数据框”。由于我更熟悉数据框,这将使我更加灵活(例如,将颜色随机分配给直方图中的条形)。我尝试编写以下代码:
#randomly assign colors to different bars in the histogram and convert table into data frame
color <- c("red", "black")
color_1 <- as.factor(sample(color, 10000, replace=TRUE, prob=c(0.5, 0.5)))
t = data.frame(t)
t$color_1 <-color_1
barplot(t, color = t$color_1)
但这会返回几个错误:
Error in `$<-.data.frame`(`*tmp*`, color_1, value = c(1L, 1L, 1L, 2L, :
replacement has 10000 rows, data has 574
由于某种原因,数据有 583 行,而不是最初在(所有行都去哪儿了!?)n = floor(rnorm(10000, 500, 100)) 命令中指定的 10,000 行。
忽略这一点,如果我假设 583 行:
color <- c("red", "black")
color_1 <- as.factor(sample(color, 574, replace=TRUE, prob=c(0.5, 0.5)))
t = data.frame(t)
t$color_1 <-color_1
barplot(t, color = t$color_1)
我收到一个新错误:
Error in barplot.default(t, color = t$color_1) :
'height' must be a vector or a matrix
谁能告诉我如何解决这个错误?
谢谢
【问题讨论】:
标签: r plot graph data-visualization data-manipulation