【问题标题】:Stacked bar in ggplot2ggplot2中的堆积条
【发布时间】:2017-11-15 22:47:56
【问题描述】:

好吧,我要疯了。所以我有一些数据有一堆列。主要是姓名、地址和其他素质。

Name       ||||   Division | | |MonthNo
John ||||  Seattle | | | | | 2
Chris|||| Seattle ||||||||| 4
Dave ||||Dallas  |||||||||| 2
Suzy |||| San Fran |||| 5
Jill | | | | Dallas |||||||||| 4

为了获得按月发生的简单计数,我这样做了:

MC$MonthNo <- factor(MC$MonthNo, levels = c(1:11), labels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"))



MCH <- ggplot(na.omit(MC), aes(MonthNo))

MCH + geom_bar(color = "black", fill = "light blue") + labs(x = "2017", y = "# of Leads") + theme(axis.line = element_line(color = "black", size = 3, linetype = "solid"), axis.text.x = element_text(face = "bold", color = "black", size = 14), axis.text.y = element_text(face = "bold", color = "black", size = 14)) + scale_y_continuous(name = "# Of Leads", breaks = c(0, 500, 1000, 1500, 2000, 2500, 3000), limits = c(0, 3000)) + theme(panel.background = element_rect(colour = "black", fill = "white"), panel.grid.minor = element_line(color = "black", size = .5), panel.grid.major = element_line(color = "black", size = .5)) 

几乎只是一个基本的条形图。

现在这个数据中有一个名为 Division 的字段。有 7 个不同的部门,例如西雅图、匹兹堡、檀香山、达拉斯、旧金山、盐湖城、新奥尔良。我想根据它们所在的分区将我的条分成堆栈。就像 7 个不同的条分成 1 个,其中 7 个段代表每个月每个分区的计数。就像在我的示例中,第 2 个月有西雅图和达拉斯。我希望一个栏中有两个部分。我这辈子都想不通。一切都是从具有几千个唯一行的 CSV 导入的。

提前致谢。

【问题讨论】:

  • 您可以将帖子标题改写为问题吗?

标签: r ggplot2


【解决方案1】:

给你。 我将您的数据保存为 csv

petey <-read.csv("Petey_data.txt")
#Adding a month variable, always good practice to
#keep original data as is and add variables
#I used the built-in month.abb constant to get 
#abbreviated month names
#assigned as factor with labels as month order
petey$Month <-factor(month.abb[petey$MonthNo], levels = month.abb)
library(ggplot2)
ggplot(petey,aes(Month))+geom_bar(aes(fill=Division))

未来请查?dput分享您的数据 还可以阅读?geom_bar 并查看示例以了解数据的排列方式。更多示例请参见网页http://ggplot2.tidyverse.org/reference/geom_bar.html

【讨论】:

  • 天哪,非常感谢。我计划最终阅读 Wickham 的书。我主要与 GIS 打交道,并想扩展一点。不过,我还有另一个问题。如果我只想使用少数几个部门,比如 7 个部门中的 3 个,我会怎么做?
  • 您可以使用df = subset(petey, Division %in% c(division1, division 2, division3)) 将数据过滤到您想要的部门(查找?subset)。然后您可以将过滤后的数据输入 ggplot,如下所示:ggplot(df, aes(Month)) + geom_bar(aes(fill=Division))
猜你喜欢
  • 1970-01-01
  • 2019-01-14
  • 1970-01-01
  • 2021-10-16
  • 2012-05-22
  • 1970-01-01
  • 2013-05-13
  • 1970-01-01
  • 2016-06-29
相关资源
最近更新 更多