首页 > 解决方案 > 带填充的 R 条形图

问题描述

我正在尝试使用填充创建一个条形图以在一个条形图中显示多个值。我能够得到每个 x 值的总数(y 值),但是当我尝试时,fill我只得到计数。

假设示例数据是一个名为的数据框data

State           Num.Class   Num.Tweets
Pennsylvania    C           98
Pennsylvania    P           10
Pennsylvania    E           174
Pennsylvania    S           70
Texas           C           233
Texas           P           42
Texas           E           30
Texas           S           26
California      C           57
California      P           32
California      E           39
California      S           20
Massachusetts   C           23
Massachusetts   P           74
Massachusetts   E           1
Massachusetts   S           3

使用ggplot我可以得到总数:

ggplot(data) + aes(x=State, y = Num.Tweets) + geom_col()

在此处输入图像描述

当我尝试fill使用gf_barorggplot() + geom_bar我得到这个而不是一个小节内的四个计数时:

gf_bar(~ State, fill =~ Num.Tweets, data = data)

# or
ggplot()+
     geom_bar(aes(x = data$Num.Class, fill = data$Num.Tweets), color = "black" , position = "stack", show.legend = FALSE)

在此处输入图像描述

我一直在看这篇文章其他文章,但没有看到我错过了什么。如果我移动变量,我会得到错误或没有输出。

例如:

gf_bar(Num.Tweets ~ State, fill =~ Num.Class, data = data)

返回Error: stat_count() must not be used with a y aesthetic.错误。

标签: r

解决方案


这是你要找的吗?

library(ggplot2)
ggplot(data, aes(x=State, y = Num.Tweets, fill = Num.Class)) +
  geom_bar(stat = "identity")

在此处输入图像描述


推荐阅读