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

R语言密度图指定图例颜色不生效问题求助

Fixing Your R Density Plot Legend Color Issue

Hey there! I see exactly what's going wrong with your legend colors—let's get this sorted quickly.

The problem lies in your legend() call: you’re using both fill = 1:6 and col = [your custom color vector], but the fill parameter is overriding the colors you want. When you set fill = 1:6, R pulls from its default color palette (the first 6 default colors) to fill the legend boxes, completely ignoring the col argument here.

Two Simple Fixes:

  1. Keep the filled box legend (match your original approach)
    Replace fill = 1:6 with your custom color vector, and remove the redundant col parameter since we’re using fill to define the box colors:

    legend(x = "topright", legend = names(df), fill = c("red", "orange", "yellow", "green", "blue", "purple"))
    
  2. Use line-style legends (more consistent with your density plots)
    Since you’re plotting lines with lines(), it makes sense to have legends that mirror this style. Use lty = 1 (for solid lines) and pair it with your custom color vector via col:

    legend(x = "topright", legend = names(df), lty = 1, col = c("red", "orange", "yellow", "green", "blue", "purple"))
    

Either of these will make your legend colors match exactly the lines you plotted. Give them a try—your density plots will look perfect in no time!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:41:55