简体   繁体   中英

Stacked bar in ggplot2

Alright, I am going crazy. So I have some data that has a bunch of columns. Mainly names, address, and other qualities.

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

To get a simple count of occurrence by Month I did this:

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)) 

Pretty much just a basic bar graph.

Now there is a field in this data called Division. There are 7 different divisions for example Seattle, Pittsburgh, Honolulu, Dallas, San Francisco, Salt Lake City, New Orleans. I want to break my bars into stacks based off of which division they are in. Like 7 different bars into 1 with the 7 segments representing the counts of each division for each month.. Like in my example Month 2 has Seattle and Dallas. I would want there to be two segments in one bar. I can't figure this out for the life of me. Everything was imported from a CSV with a couple thousand unique rows.

Thanks in advance.

Here you go. I saved your data as 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))

For the future please look up ?dput to share your data also read up on ?geom_bar and look at the examples to get an idea of how the data is arranged. More examples on the webpage at http://ggplot2.tidyverse.org/reference/geom_bar.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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