首页 > 解决方案 > 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") 

请帮忙!!

标签: rbar-chart

解决方案


这里有几个问题:

  1. 您的示例数据框被调用df1,但ggplot调用df2作为数据参数。
  2. 中的字符串df1没有用引号括起来
  3. df1缺少右括号。
  4. df1还有一个非法的列名 ,country name它没有用引号括起来。
  5. 您的数据框中没有调用任何列region,但这就是您在 ggplot 调用中使用的列。
  6. 您使用geom_barwhich 默认情况下计算数据框中的条目,而不是绘制您想要的实际计数,因此您应该指定county 轴并将其设为geom_col
  7. 我不确定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))

在此处输入图像描述


推荐阅读