【问题标题】:Error in abs(x) : non-numeric argument to mathematical function in ggplot2abs(x) 中的错误:ggplot2 中数学函数的非数字参数
【发布时间】:2021-09-18 00:47:11
【问题描述】:

我正在尝试创建一个绘图栏,但我遇到了数据问题。数据来自“列表”,我将“列表”转换为“数据框”,但我有几个问题。首先是像“Sources ”这样的单词之后的空格,我认为也在 Sources “B”之后。当我运行代码时出现错误:abs(x) 中的错误。 我很高兴知道发生了什么,因为我无法制作图表。我认为问题可能出在这些地方。

代码

S <- summary(object = results, k = 10, pause = FALSE)
df <- S$MostRelSources
df <- df %>% dplyr::rename(Sources = `Sources       `)
df$Sources <- as.character(df$Sources))
df$Articles <- as.numeric(df$Articles)
ggplot(df, aes(x=Sources, y=Articles)) +
          geom_col()

Error in abs(x) : non-numeric argument to mathematical function 

数据

dput(df)
    structure(list(Sources = structure(c("A                           ", 
    "B                       ", "C                   ", 
    "D                  ", "E            ", 
    "F                           ", "G", 
    "H                              ", "Y                         ", 
    "J                           "), class = "AsIs"), 
        Articles = c(1, 10, 7, 3, 3, 5, 5, 5, 2, 8)), row.names = c(NA, 
    10L), class = "data.frame")

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    有一个属性"AsIs" 可能来自创建的list 列的剩余部分。我们可以使用as.character 将其重新转换回character,现在代码可以工作了

    df$Sources<- as.character(trimws(df$Sources))
    

    -测试

    ggplot(df, aes(x=Sources, y=Articles)) +
               geom_col()
    

    -输出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多