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

Plotnine颜色刻度调整:如何改为浅绿到深绿渐变增强区分度

Fixing Low-Distinction Color Legend in Plotnine

Got it, let's break down why your scale_fill_gradient didn't work and fix this up:

  • You mapped color using colour = facet_var in your aes() call, which targets the outline/line/point color aesthetic.
  • scale_fill_gradient controls the fill color (used for shapes with interior space like bars or polygons), so it has no effect on points or lines from geom_point or geom_smooth.

Solution 1: If facet_var is a continuous variable

Replace the fill scale with a color scale that matches your aesthetic mapping. Use scale_colour_gradient to get that light-to-dark green gradient:

import plotnine as p9

# Your original plot setup
pretty_spk = p9.ggplot(data = data_fully_merged, 
                       mapping = p9.aes(x='index', y='value', colour = facet_var)) + \
             p9.geom_point(alpha = alpha_scale) + \
             p9.facet_grid("gender~outcome")

# Add title, smooth line, and CORRECT color scale
title_string = season_str.upper() + " " + facet_var + " " + features_str + " curves facetted by gender and outcome"
pretty_spk = pretty_spk + \
             p9.geom_smooth(method = 'loess') + \
             p9.ggtitle(title_string) + \
             p9.scale_colour_gradient(low="lightgreen", high="darkgreen") # Swapped fill for colour

# Display the plot
print(pretty_spk)

Solution 2: If facet_var is a discrete variable

Gradient scales are designed for continuous data. If facet_var is categorical, use a discrete green palette instead. You can use a built-in palette or define custom shades:

# Option 1: Use built-in Greens palette from ColorBrewer
pretty_spk = pretty_spk + \
             p9.geom_smooth(method = 'loess') + \
             p9.ggtitle(title_string) + \
             p9.scale_colour_brewer(palette="Greens")

# Option 2: Define custom green shades (adjust the hex codes to your preference)
custom_greens = ["#e8f5e9", "#c8e6c9", "#a5d6a7", "#66bb6a", "#2e7d32"]
pretty_spk = pretty_spk + \
             p9.geom_smooth(method = 'loess') + \
             p9.ggtitle(title_string) + \
             p9.scale_colour_manual(values=custom_greens)

Quick Reminder

Always match your scale function to the aesthetic you mapped in aes():

  • Use scale_colour_* when you set colour = ...
  • Use scale_fill_* when you set fill = ...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 15:47:30