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

如何更简便地在levelplot右上角添加均值与中位数?

问题:如何在levelplot右上角自动添加数据均值和中位数

在使用levelplot绘制可视化图表时,希望将数据的均值和中位数添加到图表右上角,而非作为轴标签。目前手动计算并添加的方式十分繁琐,求简便实现方法。

现有代码及数据示例

p1=levelplot(R_land, par.settings=mapTheme, at=my.brks, colorkey=myColorkey , 
margin=F,main=list('IMD'),xlab = 'Mean=0.728
Median=0.368')
print(p1) 

数据:

head(Gm,n=10)
         x     y       Gm
 1:  66.50 38.50 1.611716
 2:  66.75 38.50 1.825812
 3:  67.00 38.50 1.873785
 4:  67.25 38.50 1.936212
 5:  67.50 38.50 2.025188
 6:  67.75 38.50 1.982969
 7:  68.00 38.50 1.696595
 8:  68.25 38.50 1.740960
 9:  68.50 38.50 1.774679
10:  68.75 38.50 1.866798

R_land<-rasterFromXYZ(Gm)  # 注:原代码中rasterfromXYZ应为rasterFromXYZ,注意大小写

解决方案

核心思路是自动计算栅格数据的统计量,再通过grid绘图系统将文本定位到右上角,无需手动计算。

步骤1:自动计算均值和中位数

利用栅格包的cellStats()函数直接对栅格对象计算全局统计量,自动忽略NA值:

library(raster)
library(lattice)
library(grid)

# 计算均值和中位数
mean_val <- cellStats(R_land, mean, na.rm = TRUE)
median_val <- cellStats(R_land, median, na.rm = TRUE)

方法一:通过main参数直接嵌入统计信息

将统计文本设置为main内容,利用unit()指定右上角位置:

# 构建统计文本(保留3位小数)
stats_text <- paste0("Mean = ", round(mean_val, 3), "\nMedian = ", round(median_val, 3))

p1 <- levelplot(R_land, par.settings = mapTheme, at = my.brks, colorkey = myColorkey, 
                margin = FALSE,
                main = list(label = stats_text,
                           x = unit(0.95, "npc"),  # 右上角相对坐标
                           y = unit(0.95, "npc"),
                           just = c("right", "top"),  # 文本右上角对齐坐标点
                           gp = gpar(fontsize = 10)))  # 设置字体大小

# 若需要保留原标题"IMD",额外添加到左上角
grid.text("IMD", x = unit(0.05, "npc"), y = unit(0.95, "npc"), 
          just = c("left", "top"), gp = gpar(fontsize = 12, fontface = "bold"))

print(p1)

方法二:绘图后用grid.text添加文本(更灵活)

先绘制常规levelplot,再用grid.text()将统计文本定位到右上角:

# 绘制基础图表
p1 <- levelplot(R_land, par.settings = mapTheme, at = my.brks, colorkey = myColorkey, 
                margin = FALSE, main = "IMD")
print(p1)

# 添加均值和中位数文本
grid.text(paste0("Mean = ", round(mean_val, 3)), 
          x = unit(0.95, "npc"), y = unit(0.92, "npc"), 
          just = "right", gp = gpar(fontsize = 10))
grid.text(paste0("Median = ", round(median_val, 3)), 
          x = unit(0.95, "npc"), y = unit(0.88, "npc"), 
          just = "right", gp = gpar(fontsize = 10))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 02:20:54