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_varin youraes()call, which targets the outline/line/point color aesthetic. scale_fill_gradientcontrols the fill color (used for shapes with interior space like bars or polygons), so it has no effect on points or lines fromgeom_pointorgeom_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 setcolour = ... - Use
scale_fill_*when you setfill = ...
内容的提问来源于stack exchange,提问作者lll
相关产品推荐
相关产品推荐

