scales_fill_continuous不起作用(ggplot2)
我有一个数据:
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)
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
不起作用.该图是黑色和灰色的.
scale_fill_continuous
doesn't work. The graph is black and gray.
Tks.
我认为问题是填充有 nrow(df_1)
个值,但只需要100个即可.可以通过预先计算bin的位置和计数并使用 geom_col
进行绘制来解决,但是更巧妙的解决方案是使用 stat
.stat stat
应该用于计算变量(例如 stat(count)
-参见?geom_histogram
),但是我们可以给它向量1:nbin
,并且有效.
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")
由 reprex软件包(v0.3.0)于2020-01-19创建
Created on 2020-01-19 by the reprex package (v0.3.0)