使用第三个变量作为geom_histogram中的填充美学

问题描述 投票:0回答:1

我正在尝试通过使用连续变量填充直方图来向直方图添加额外的维度。但是,以下语法为我提供了灰色条:


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()

enter image description here

使用具有因子转换变量的离散比例有效:

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()

enter image description here

我们可以清楚地看到,这增加了信息。也就是说,HP似乎与MPG成反比。

这正是我想要实现的。

任何人都可以解释这种行为以及如何避免这种行为吗?

r ggplot2 gradient fill continuous
1个回答
0
投票

我对这个问题尚不完全清楚,但是该图看起来是这样,因为您实际上将HP视为一个数值变量,因此将HP视为一个因素。

通常,直方图用于显示有关单个变量而不是两个变量的信息。在这种情况下,您对两个变量之间的关系很感兴趣,因此使用另一个绘图可能更合适。您是否有理由不想使用散点图来显示这种关系?散点图通常更适合比较两个数字变量。

我认为这更清楚地显示了同一件事(即,HP和MPG成反比)。

ggplot(mtcars, aes(x = mpg, y = hp)) +
  geom_point()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.