简体   繁体   English

R 条 plot 带填充

[英]R bar plot with fill

I am trying to create a bar plot using fill to show multiple values within one bar.我正在尝试使用填充创建一个条形 plot 以在一个条形中显示多个值。 I am able to get totals (y value) per the x-value, but when I try to fill I just get the count.我可以根据 x 值获得总计(y 值),但是当我尝试fill时,我只会得到计数。

Say the example data is a data frame named data :假设示例数据是一个名为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

Using ggplot I can get the totals:使用ggplot我可以得到总数:

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

在此处输入图像描述

When I try fill ing with gf_bar or ggplot() + geom_bar I get this instead of the four counts within one bar:当我尝试用gf_barggplot() + geom_bar fill ,我得到了这个而不是一个小节内的四个计数:

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)

在此处输入图像描述

I've been looking at this post and others but don't see what I am missing.我一直在看这篇文章其他文章,但没有看到我错过了什么。 If I shift the variables I get an error or no output.如果我移动变量,我会得到一个错误或没有 output。

For example:例如:

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

returns the Error: stat_count() must not be used with ay aesthetic.返回Error: stat_count() must not be used with ay aesthetic. error.错误。

Is this what you're looking for?这是你要找的吗?

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

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM