我正在尝试通过使用连续变量填充直方图来向直方图添加额外的维度。但是,以下语法为我提供了灰色条:
ggplot(mtcars, aes(x = mpg, fill = hp)) +
geom_histogram(aes(y = (..count..)/sum(..count..)), binwidth = 2) +
scale_y_continuous(label = function(x) paste0(round(x *100), "%")) +
labs(x = "miles per gallon",
y = "percentage of cars",
fill = "horsepower") +
theme(legend.position = c(.8, .8)) +
scale_fill_continuous()
使用具有因子转换变量的离散比例有效:
ggplot(mtcars, aes(x = mpg, fill = factor(hp))) +
geom_histogram(aes(y = (..count..)/sum(..count..)), binwidth = 2) +
scale_y_continuous(label = function(x) paste0(round(x *100), "%")) +
labs(x = "miles per gallon",
y = "percentage of cars",
fill = "horsepower") +
theme(legend.position = c(.8, .8)) +
scale_fill_discrete()
我们可以清楚地看到,这增加了信息。也就是说,HP似乎与MPG成反比。
这正是我想要实现的。
任何人都可以解释这种行为以及如何避免这种行为吗?