plotnine中如何将变量映射到scale_color_gradient?
Fixing the Gradient Fill Warning in ggplot (Plotnine) Histogram
Let's break down what's happening here and resolve that warning for you:
The Root Issue
Your code maps the bin count to the fill aesthetic in geom_histogram(aes(fill='..count..')), but then you're trying to adjust the color scale with scale_color_gradient(). These are two distinct aesthetic properties in ggplot:
fillcontrols the interior color of the histogram barscolorcontrols the border color of the bars
Since you haven't mapped any variable to the color aesthetic, Plotnine throws that warning because it can't generate a legend for an aesthetic that isn't being used in your plot.
The Simple Fix
Just replace scale_color_gradient() with scale_fill_gradient() to match the aesthetic you're actually using for the bar fill:
import pandas as pd from plotnine import ggplot, aes, geom_histogram, scale_fill_gradient gg = pd.DataFrame() gg['x'] = u # Assuming 'u' is your pre-defined dataset variable p = ggplot(aes(x='x'), gg) + geom_histogram(aes(fill='..count..'), binwidth=0.1) p = p + scale_fill_gradient(low='blue', high='white') print(p)
Extra Context
- If you wanted the bar border color to also use a gradient based on count, you'd add
color='..count..'to theaes()insidegeom_histogram, and then you could use bothscale_fill_gradient()andscale_color_gradient()(though this might make the histogram look cluttered for most use cases). - The
..count..variable is a special computed value in ggplot that returns the number of observations in each bin, which is exactly what you're using to drive your fill gradient here.
内容的提问来源于stack exchange,提问作者bill fite
相关产品推荐
相关产品推荐

