英文:
ggplot2 Unable to fill histogram with color by column
问题
在这里,您尝试比较一个变量的计数和另一个变量的频率,因此我有
ggplot(data = Q11b) +
geom_histogram(mapping = aes(x = WEIGHT2, fill = EDUCA), binwidth = 5)
在这里,WEIGHT2是连续变量,我尝试让'EDUCA'基于填充,'EDUCA'是一个包含1-6数字的列。因此,我期望直方图显示分布的图表,具有6种颜色的图例,就像我在许多示例中看到的那样。
而实际上,我得到了这个:
你们有任何关于我哪里出错的想法吗?我尝试了geom_freqpoly(),出现了相同的问题。我还尝试将EDUCA部分更改为另一列,但看不出我错在哪。任何帮助将不胜感激。
英文:
So, I am trying to compare count of a variable by frequency of another, so I have
ggplot(data = Q11b) +
geom_histogram(mapping = aes(x = WEIGHT2, fill = EDUCA), binwidth = 5)
In this, WEIGHT2 is continuous, and what I'm trying to have the fill based on 'EDUCA', which is a column of number 1-6. So, I am expecting the histogram to show a plot of the distribution with 6 colors in a legends, like I've seen in many examples.
Instead, I get this:
Do you guys have any idea where I went wrong? I tried a geom_freqpoly() and had the same issue. I also tried changing the EDUCA part to a different column and couldn't see what I was doing wrong.
Any help would be appreciated
答案1
得分: 1
以下是代码部分的翻译,其他内容不翻译:
set.seed(1)
Q11b <- subset(data.frame(WEIGHT2 = rgamma(1e5, 3) * 20 + 100,
EDUCA = sample(6, 1e5, TRUE)), WEIGHT2 < 320)
library(ggplot2)
ggplot(data = Q11b) +
geom_histogram(mapping = aes(x = WEIGHT2, fill = EDUCA), binwidth = 5)
#> Warning: The following aesthetics were dropped during statistical transformation: fill
#> i This can happen when ggplot fails to infer the correct grouping structure in
#> the data.
#> i Did you forget to specify a `group` aesthetic or to convert a numerical
#> variable into a factor?
ggplot(data = Q11b) +
geom_histogram(mapping = aes(x = WEIGHT2, fill = factor(EDUCA)), binwidth = 5)
Created on 2023-02-13 with reprex v2.0.2
英文:
The following data set should approximate yours according to your description:
set.seed(1)
Q11b <- subset(data.frame(WEIGHT2 = rgamma(1e5, 3) * 20 + 100,
EDUCA = sample(6, 1e5, TRUE)), WEIGHT2 < 320)
And we get a similar result using your code (as well as a warning being emitted):
library(ggplot2)
ggplot(data = Q11b) +
geom_histogram(mapping = aes(x = WEIGHT2, fill = EDUCA), binwidth = 5)
#> Warning: The following aesthetics were dropped during statistical transformation: fill
#> i This can happen when ggplot fails to infer the correct grouping structure in
#> the data.
#> i Did you forget to specify a `group` aesthetic or to convert a numerical
#> variable into a factor?
If we simply follow the advice and convert EDUCA
to a factor, we get our colored groups:
ggplot(data = Q11b) +
geom_histogram(mapping = aes(x = WEIGHT2, fill = factor(EDUCA)), binwidth = 5)
<sup>Created on 2023-02-13 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论