如何在 R 中创建并排条形图? (-0.01 * height 中的错误:二元运算符的非数字参数)
How to create a side by side barplot in R? (Error in -0.01 * height : non-numeric argument to binary operator)
我有一个类型的矩阵
1 2 3 4 5
A " 9" "27" " 0" "46" "50"
B "46" "34" "27" "22" " 3"
我正在尝试用
创建条形图
barplot(df, beside=TRUE)
但我收到一条错误消息
Error in -0.01 * height : non-numeric argument to binary operator
而且我不知道出了什么问题。我希望条形图是一个并排的条形图,从 1 到 5,就像列名一样,每个数字有两个并排的条形图(A 和 B)。
您的号码以字符形式存储,这就是您收到 non-numeric argument
错误的原因。试试这个:
df <- matrix(c("1","2","3","4"), ncol = 2) #use your own data, just to make it reproducible
df <- apply(df,1, as.numeric)
barplot(df, beside=TRUE)
这是一个可重现的例子:
df <- matrix(c("9", "27", "0", "46", "50", "46", "34", "27", "22", "3"), nrow = 2, ncol = 5, byrow = TRUE,
dimnames = list(c("A", "B"),
c("1", "2", "3", "4", "5")))
class(df) <- "numeric"
barplot(df, beside=TRUE)
这里是一个答案的参考,概述了从字符矩阵转换为数字矩阵的选项:Convert character matrix into numeric matrix
我有一个类型的矩阵
1 2 3 4 5
A " 9" "27" " 0" "46" "50"
B "46" "34" "27" "22" " 3"
我正在尝试用
创建条形图barplot(df, beside=TRUE)
但我收到一条错误消息
Error in -0.01 * height : non-numeric argument to binary operator
而且我不知道出了什么问题。我希望条形图是一个并排的条形图,从 1 到 5,就像列名一样,每个数字有两个并排的条形图(A 和 B)。
您的号码以字符形式存储,这就是您收到 non-numeric argument
错误的原因。试试这个:
df <- matrix(c("1","2","3","4"), ncol = 2) #use your own data, just to make it reproducible
df <- apply(df,1, as.numeric)
barplot(df, beside=TRUE)
这是一个可重现的例子:
df <- matrix(c("9", "27", "0", "46", "50", "46", "34", "27", "22", "3"), nrow = 2, ncol = 5, byrow = TRUE,
dimnames = list(c("A", "B"),
c("1", "2", "3", "4", "5")))
class(df) <- "numeric"
barplot(df, beside=TRUE)
这里是一个答案的参考,概述了从字符矩阵转换为数字矩阵的选项:Convert character matrix into numeric matrix