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

使用ggplot绘制熔解时间序列时JCO调色板未生效问题求助

问题解决:JCO调色板未生效的修复方案
  • 问题根源:你在ggplot中用colour=variable定义了线条颜色的映射,但调用的是scale_fill_jco()——这个函数是用来设置填充色(fill)的,和线条颜色(colour)的美学不匹配,所以默认颜色没被覆盖。

  • 修正后的完整代码:

# 加载必要的包
library(ggplot2)
library(ggsci)
library(reshape2)  # 用于melt函数
library(scales)    # 用于日期格式化

# 数据定义
df <- data.frame(
  V1 = c(
    0.299709245928855, 0.264898804581009, 0.0514762211257873, 0.172528797343094,
    0.286692151182817, 0.381306320393445, 0.209173997269107, 0.0271853802231936,
    0.0773644637950056, 0.100304007028023
  ),
  V2 = c(
    0.0656779733249077, 0.252630359185351, 0.35086728952018, 0.337186818513385,
    0.495255439470686, 0.913847169790918, 0.358945167549019, 0.849737426926668,
    1.0342232107347, 1.2839730181513
  ),
  V3 = c(
    0.11712306002031, 0.326976704286807, 0.44465221799287, 0.428882415544564,
    0.606684040009608, 1.13251218973981, 0.454452665889777, 1.05901363917576,
    1.29908926601187, 1.63183343004054
  ),
  DATE = as.Date(c(
    "1971-01-01", "1971-01-02", "1971-01-03", "1971-01-04", "1971-01-05",
    "1971-01-06", "1971-01-07", "1971-01-08", "1971-01-09", "1971-01-10"
  ))
)

# 数据重塑
mdf <- melt(df, id.vars="DATE")

# 绘图代码(修正颜色映射)
g <- ggplot(data=mdf, aes(x=DATE, y=value, group=variable, colour=variable)) +
  geom_line(linewidth=0.05) +
  scale_color_jco(
    name="",  # 移除图例标题
    breaks=c("V1", "V2", "V3"),
    labels=c("First", "Second", "Third")
  ) +
  scale_x_date(
    breaks=date_breaks("1 years"), 
    labels=date_format("%Y"), 
    expand=c(0, 0)
  ) +
  labs(y="Mean precipitation(mm)", x="Year")

# 显示图表
print(g)
  • 关键修正说明:
    1. 将scale_fill_jco()替换为scale_color_jco(),匹配colour=variable的美学映射;
    2. 确保代码开头加载了所有依赖包,避免因包未加载导致的功能失效;
    3. 保持name=""参数,实现移除图例标题的需求;
    4. 修正了标签中的小写"third"为大写"Third",保持格式统一(可选)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:25:35