在R中使用条形图时出错:宽度错误/2:二进制运算符的非数字参数

在R中使用条形图时出错:宽度错误/2:二进制运算符的非数字参数,r,bar-chart,R,Bar Chart,我想用R做条形图 # the data > dput(CK) structure(c(2L, 1L, 12L, 2L, 24L, 26L, 17L, 0L, 7L, 2L, 0L, 16L, 43L, 1L, 3L, 4L, 1L, 5L), .Dim = c(6L, 3L), .Dimnames = structure(list( c("BL 1", "BL 2", "IM", "ML", "MSL", "LAR"), c("nicht", "gering", "hoch")), .

我想用R做条形图

# the data
> dput(CK)
structure(c(2L, 1L, 12L, 2L, 24L, 26L, 17L, 0L, 7L, 2L, 0L, 16L, 
43L, 1L, 3L, 4L, 1L, 5L), .Dim = c(6L, 3L), .Dimnames = structure(list(
c("BL 1", "BL 2", "IM", "ML", "MSL", "LAR"), c("nicht", "gering", 
"hoch")), .Names = c("", "")), class = "table")

> dput(AR)
structure(c(62L, 1L, 16L, 8L, 25L, 1L, 0L, 0L, 3L, 0L, 0L, 15L, 
0L, 1L, 3L, 0L, 0L, 31L), .Dim = c(6L, 3L), .Dimnames = structure(list(
c("BL 1", "BL 2", "IM", "ML", "MSL", "LAR"), c("nicht", "gering", 
"hoch")), .Names = c("", "")), class = "table")

# the plots
barplot(t(CK), col=c("#66c2a5","#fc8d62", "#8da0cb"), space=0.04, font.axis=2, "CK")
barplot(t(AR), col=c("#66c2a5","#fc8d62", "#8da0cb"), space=0.04, font.axis=2, "AR")
第一个情节很好。第二个绘图抛出错误:

宽度错误/2:二进制运算符的非数值参数 此外:警告信息: 默认值(宽度):参数不是数字或逻辑参数:返回NA


是什么导致非常相似的表的绘图中出现不同的行为?

首先,错误源于第一次调用
条形图。由于这两个
barplot
调用都不会生成图形,因此我不能完全确定您的输出图应该是什么样子

除此之外,这里还有一种使用
ggplot2
的替代方法,我们可以使用
facet\u wrap
一次性绘制
CK
AR
数据

library(tidyverse);
df <- bind_rows(
    list(
        CK = CK %>% as.data.frame.matrix() %>% rownames_to_column("x"),
        AR = AR %>% as.data.frame.matrix() %>% rownames_to_column("x")),
    .id = "id")
df %>%
    gather(key, value, -id, -x) %>%
    ggplot(aes(x = id, y = value, fill = key)) +
    geom_bar(stat = "identity") +
    facet_wrap(~id, scales = "free_x")

对不起,如何在问题中添加情节?您是在问吗?如果是这样的话,请看链接。@ke.re我也用不同的情节更新了我的帖子,可能更接近你想要的。请看一看,谢谢。我认为问题在于使用
table()
创建条形图数据时。我切换到了ggplot,但我不喜欢随之而来的变量顺序的重组。@ke.re通过改变
因子
级别的顺序来重新安排变量的顺序是相当容易的(这里有很多关于该主题的帖子)。
ggplot
语法绝对是独特的,但只要你仔细想想,它就非常优雅和直截了当了。
df %>%
    gather(key, value, -id, -x) %>%
    ggplot(aes(x = x, y = value, fill = key)) +
    geom_bar(stat = "identity") +
    facet_wrap(~id, scales = "free_x")