Glae-Nara
Glae-Nara

Reputation: 13

Splitting bars in ggplot2

I'm super new at this and starting in the middle while working forwards and backwards simultaneously, so forgive me if this is a super basic question.

I have this code:

mh<-read.csv("mkhz_meta.csv")

msub<-mh[complete.cases(mh[ , 29]),]

msub2 <- subset(msub, Target.Fungal.Phylum!= "a")

png("J_Weighted_2_FungalPhylum.png", width= 800, height=600)
ggplot(aes(x = Target.Fungal.Phylum, fill= Concl..Weighted.nestedness), data =     msub2) + geom_bar(position = "dodge")+
xlab("Target Fungal Phylum")+ ylab("Count")+ ggtitle("Weighted vs. Primer  Specificity")+
theme_bw()+
scale_fill_grey()+
theme(axis.text.x =element_text(hjust = 0.5, size =8, angle= 0), 
    axis.text.y =element_text(size= 10), 
    legend.title=element_blank(), 
    legend.text=element_text(size=10), 
    axis.title.x =element_text(size=10),
    axis.title.y =element_text(size=10))+
theme(panel.grid.minor = element_blank(),
    panel.grid.major=element_blank(),
    strip.background = element_blank(),
    strip.text.x=element_text(size=14),
    panel.border = element_rect(colour = "black"))
 dev.off()

It returns this graph:

Binary vs. Sequencing

There is one count of non-nested morphotyping, and no count of nested morphotyping - I can't figure out how to have the 'morphotyping' bar be split to reflect this. Any help is greatly appreciated!

Upvotes: 1

Views: 77

Answers (2)

neilfws
neilfws

Reputation: 33782

You can use tidyr::complete to add missing counts to your data.

Sample data:

mydata <- structure(list(platform = c("454", "454", "454", "454", "454", 
"454", "454", "454", "454", "454", "Morphotyping", "Sanger", 
"Sanger", "Sanger", "Sanger", "Sanger", "Sanger"), is_nested = c("nested", 
"not nested", "nested", "nested", "nested", "nested", "nested", 
"not nested", "nested", "not nested", "not nested", "nested", 
"nested", "nested", "not nested", "nested", "not nested")), .Names = 
c("platform", 
"is_nested"), row.names = c(NA, -17L), class = c("tbl_df", "tbl", 
"data.frame"), spec = structure(list(cols = structure(list(platform = 
structure(list(), class = c("collector_character", 
"collector")), is_nested = structure(list(), class = 
c("collector_character", 
"collector"))), .Names = c("platform", "is_nested")), default = 
structure(list(), class = c("collector_guess", 
"collector"))), .Names = c("cols", "default"), class = "col_spec"))

Code to count and plot:

library(tidyverse)
mydata %>% 
  count(platform, is_nested) %>% 
  complete(platform, is_nested) %>% 
  ggplot(aes(platform, n)) + 
    geom_col(aes(fill = is_nested), 
             position = position_dodge())

enter image description here

Upvotes: 1

DMR
DMR

Reputation: 1473

Try adding:

+ scale_fill_discrete(drop=FALSE) + scale_x_discrete(drop=FALSE) to your plot command to preserve the empty plot bins.

Upvotes: 0

Related Questions