R语言密度图指定图例颜色不生效问题求助
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:
Keep the filled box legend (match your original approach)
Replacefill = 1:6with your custom color vector, and remove the redundantcolparameter since we’re usingfillto define the box colors:legend(x = "topright", legend = names(df), fill = c("red", "orange", "yellow", "green", "blue", "purple"))Use line-style legends (more consistent with your density plots)
Since you’re plotting lines withlines(), it makes sense to have legends that mirror this style. Uselty = 1(for solid lines) and pair it with your custom color vector viacol: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

