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

如何为stat_contour_filled绘制的图形添加连续色条?

问题解决方法

要将stat_contour_filled生成的离散色块图例替换为连续色条,需调整绘图函数和颜色标度,具体操作如下:

核心修改步骤

  • 替换stat_contour_filled为stat_contour_tile(要求ggplot2版本≥3.4.0,该函数支持基于连续数值的填充,适配连续色条图例)
  • 将scale_fill_manual(离散配色)替换为scale_fill_gradientn(连续配色),复用你定义的颜色向量作为连续色阶

修改后的完整代码

ggpolar(pole = "N", max.lat = 90, min.lat = 30,
    land.fill.colour = "#D9D9D9", land.outline.colour = "#343434", 
    plt.lat.labels = FALSE) +
ggtitle("A") +
theme(plot.title = element_text(hjust = 0, family = "Arial", size = 22, face = "bold")) +
# 替换为stat_contour_tile,映射连续z值到fill
stat_contour_tile(data = change_ratio_df, 
                  aes(x = lon, y = lat, z = change_ratio, fill = after_stat(z)), 
                  breaks = seq(-2, 2, by = 0.2)) + 
# 使用连续色阶,保留原配色
scale_fill_gradientn(colors = c("#053061", "#124580", "#1D5FA1", "#2D74B3", "#3A86BD", "#529AC7",
                            "#74B1D4", "#95C5DE", "#B1D4E6", "#CAE1ED", "#DFEBF2", "#EDF2F5",
                            "#FAF3ED", "#FCE8D9", "#FCD8C0", "#FAC0A2", "#F5A684", "#EB896C",
                            "#DB6C56", "#CC4F43", "#BD2F32", "#A81428", "#850C24", "#66001F" ),
                    limits = c(-2, 2))+  
geom_point(data = selected_points, aes(x = lon, y = lat), color = "#343434", size = 0.5) +
geom_path(data = line_df,aes(X, Y, group = L1),colour = "#343434") +
theme(
plot.background = element_rect(fill = NA, color = NA),  # 图背景透明
panel.background = element_rect(fill = NA, color = NA),  # 绘图区背景透明
legend.position = "right",
legend.key.width = unit(2, "line"),
legend.title = element_text(family = "Arial", size = 12),
legend.text = element_text(size = 12),
axis.title = element_blank(),
axis.text = element_text(family = "Arial", size = 12),
axis.ticks = element_blank()
)

低版本ggplot2备选方案

如果无法升级ggplot2,可使用metR包实现:

  1. 安装并加载包:install.packages("metR"); library(metR)
  2. 替换原stat_contour_filled为geom_contour_fill(data = change_ratio_df, aes(x = lon, y = lat, z = change_ratio), breaks = seq(-2, 2, by=0.2))
  3. 同样用scale_fill_gradientn替换scale_fill_manual,配色保持不变

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 10:33:21