问题
I have a data:
df_1 <- data.frame(
x = replicate(
n = 2, expr = rnorm(n = 3000, mean = 100, sd = 10)
),
y = sample(x = 1:3, size = 3000, replace = TRUE)
)
And the follow function:
library(tidyverse)
ggplot(data = df_1, mapping = aes(x = x.1, fill = x.1)) +
geom_histogram(color = 'black', bins = 100) +
scale_fill_continuous(low = 'blue', high = 'red') +
theme_dark()
scale_fill_continuous doesn't work. The graph is black and gray.
Tks.
回答1:
The problem, I think, is that there are nrow(df_1) values for fill, but only 100 are needed. This could be solved by pre-calculating the bin positions and counts and plotting with geom_col, but a neater solution is to use stat. stat is supposed to be for computed variables (e.g. stat(count) - see ?geom_histogram) but we can give it the vector 1:nbin and it works.
df_1 <- data.frame(
x = replicate(n = 2, expr = rnorm(n = 3000, mean = 100, sd = 10)),
y = sample(x = 1:3, size = 3000, replace = TRUE)
)
library(tidyverse)
nbins <- 100
ggplot(data = df_1, mapping = aes(x = x.1, fill = stat(1:nbins))) +
geom_histogram(bins = nbins) +
scale_fill_continuous(low = "red", high = "blue")

Created on 2020-01-19 by the reprex package (v0.3.0)
回答2:
The aes fill should be stat(count) rather than x.1
ggplot(data = df_1, mapping = aes(x = x.1, fill = stat(count))) +
geom_histogram(color = 'black', bins = 100) +
scale_fill_continuous(type = "gradient", low = "blue", high = "red") +
theme_dark()
来源:https://stackoverflow.com/questions/59811647/scales-fill-continuous-doesnt-work-ggplot2