根据数据集的变量在R中着色条形图

Colouring barplot in R according to variable of data set

我正在尝试根据年份在 R 中为条形图的条形着色。 我没有成功使用 read.table,这就是为什么我尝试采用这种方法: barplot() different colors of grey for bars based on number of categories in a column

我试过创建一个像这样的迷你数据框。这非常有效

j=data.frame(plot=c("N10-11","N10-14","N13-11","N13-14"),dbh=c("60.6","68.5","55.6","61.5"),year=c("2011","2014","2011","2014"))

正在尝试修改此代码

barplot(x$cov, names.arg = x$exon, 
    ylab = "read depth" , 
    col = gray.colors(length(unique(x$exon)))[as.factor(x$exon)])

到我的数据集(即使是最简单的方法......)结果

Error in barplot.default(j$dbh) : 'height' must be a vector or a matrix

我一定是遗漏了一个非常基本的东西。 你能帮我解决我的问题吗? 此外,我想使用自定义颜色而不是让 R 自动选择它们 - 我怎样才能做到这一点?

问候 妮可

#data in right format, height-variable needs to be numeric

j=data.frame(plot=c("N10-11","N10-14","N13-11","N13-14"),
             dbh=as.numeric(c("60.6","68.5","55.6","61.5")),
             year=c("2011","2014","2011","2014"))
#check this
> str(j)
'data.frame':   4 obs. of  3 variables:
 $ plot: Factor w/ 4 levels "N10-11","N10-14",..: 1 2 3 4
 $ dbh : num  60.6 68.5 55.6 61.5
 $ year: Factor w/ 2 levels "2011","2014": 1 2 1 2

mycols <- c("red","blue")

barplot(j$dbh, names.arg = j$plot, ylab = "dbh" , 
    col = mycols[j$year], ylim=c(0,70))