You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

绘制Lasagna图时遭遇‘非数值参数’错误的技术求助

解决Lasagna图绘制中的non-numeric argument to binary operator错误

错误原因

直接将包含字符型fips列的数据框转换为矩阵,会导致整个矩阵变为字符类型。lasagna()函数在计算数值范围(zlim)时,对字符值执行减法操作,触发该错误。

解决方案

  1. 将fips列设置为矩阵的行名,移除原列以确保矩阵仅包含数值型数据
  2. 修正颜色参数拼写错误:"virdis"应为viridis(需加载viridis包),或使用其他有效颜色向量

修正后的完整代码

# 加载依赖包
library(devtools)  
install_github("swihart/lasagnar")                                                               
library(fields)
library(lasagnar)   
library(ggplot2)
library(reshape2)
library(RColorBrewer)
library(colorspace) 
library(viridis) # 加载viridis包使用对应色板

# 构造示例数据
lg1 <- structure(list(fips = c("36033", "48015", "48039", "48041", "48051", 
"48071"), `1900` = c(1, 1, 1, 1, 1, 1), `1901` = c(0, 0, 0, 0, 
0, 0), `1903` = c(0, 0, 0, 0, 0, 0), `1904` = c(0, 0, 0, 0, 0, 
0), `1906` = c(0, 0, 0, 0, 0, 0), `1908` = c(0, 0, 0, 0, 0, 0
), `1909` = c(0, 0, 1, 0, 0, 0), `1910` = c(0, 0, 0, 0, 0, 0), 
    `1911` = c(0, 0, 0, 0, 0, 0), `1912` = c(0, 0, 0, 0, 0, 0
    ), `1913` = c(0, 0, 0, 0, 0, 0), `1915` = c(0, 1, 1, 0, 0, 
    1), `1916` = c(0, 0, 0, 0, 0, 0), `1917` = c(0, 0, 0, 0, 
    0, 0), `1918` = c(0, 0, 0, 0, 0, 0), `1919` = c(0, 0, 0, 
    0, 0, 0), `1920` = c(0, 0, 0, 0, 0, 0), `1921` = c(0, 0, 
    0, 0, 0, 0), `1923` = c(0, 0, 0, 0, 0, 0)), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

# 预处理:提取数值列,将fips设为行名
row.names(lg1) <- lg1$fips
lg1_matrix <- as.matrix(lg1[, -match("fips", colnames(lg1))])
names(dimnames(lg1_matrix)) <- c('Location','Year')

# 绘制Lasagna图
lasagna(lg1_matrix, gridlines = TRUE, col = rev(viridis(10)), legend = TRUE, main = "")

额外说明

  • 若不想使用viridis色板,可替换为RColorBrewer的色板,例如col = rev(brewer.pal(9, "Blues"))
  • 矩阵必须全部为数值型,这是lasagnar包绘图的基础要求

内容的提问来源于stack exchange,提问作者tchoup

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 13:55:17