r - R中的条形图对齐问题
问题描述
给定的数据框由不同的行组成,其中一些样本包含 3 列
df1 <- data.frame( income = c(>20K, <=20K, >20K, <=20K),
country name = c(Cuba, Cuba, USA, USA),
count = c(10, 12, 21, 27)
我想用收入填充国家名称绘制条形图。没有得到正确的结果
这是我的代码
ggplot(df2, aes(x = region)) +
geom_bar(aes(fill = income), position = "fill")
请帮忙!!
解决方案
这里有几个问题:
- 您的示例数据框被调用
df1
,但ggplot
调用df2
作为数据参数。 - 中的字符串
df1
没有用引号括起来 df1
缺少右括号。df1
还有一个非法的列名 ,country name
它没有用引号括起来。- 您的数据框中没有调用任何列
region
,但这就是您在 ggplot 调用中使用的列。 - 您使用
geom_bar
which 默认情况下计算数据框中的条目,而不是绘制您想要的实际计数,因此您应该指定count
y 轴并将其设为geom_col
- 我不确定
position = "fill"
这里在做什么。
无论如何,如果您解决了所有这些问题,它似乎可以正常工作。
df1 <- data.frame( income = c(">20K", "<=20K", ">20K", "<=20K"),
region = c("Cuba", "Cuba", "USA", "USA"),
count = c(10, 12, 21, 27))
ggplot(df1, aes(x = region, y = count)) +
geom_col(aes(fill = income))
推荐阅读
- reactjs - 如何在令牌过期时创建注销
- nginx - 无法将 keyrock 与未加载的 nginx、css 和 js 文件集成
- buildbot - BuildBot:并行执行构建步骤
- amazon-web-services - AWS PowerShell 检索 Elastic Beanstalk 环境的源包的存储桶名称和 S3 密钥
- youtube-api - 实时流的自适应比特率摄取(发布)
- php - 使用php将数组附加到redis中的现有键
- python - How to load iframe in Python Django?
- python - req.has_data() 在 python 3.7 中不起作用
- sonarqube - 为什么我会收到 Sonarqube 'License Corrupted' 错误?
- c++ - 递归函数c ++上的分段错误