100% Stacked bar Chart in R

Laura Walker picture Laura Walker · Feb 16, 2017 · Viewed 7.3k times · Source

Good Morning,

I'm trying to get this data in a 100% Stacked Bar chart in R

        Federal Non Federal
2006    46753094    74740716
2007    43397314    74834857
2008    43962330    71051132
2009    42238038    72987898
2010    49546221    75232382
2011    48730233    76333479
2012    49316564    74669993
2013    48198329    75644892
2014    46630540    74783207
2015    46214781    75004771
2016    47625256    73744148

so that it can look like this: enter image description here

I will be the first to admit that it certainly doesn't like an exciting map but it's needed nonetheless.

I've tried to do the code as explained here but it didn't work.

This is what I did:

>     g <- ggplot(FedNonFed, aes(FedNonFed))
>     g + geom_bar(aes(fill = FedNonFed), position = "fill")

Not the graph I needed.

g <- ggplot(FedNonFed, aes(FY))
g + geom_bar(aes(fill = FedNonFed), position = "fill")
g + geom_bar(aes(fill = TotalExpense), position = "fill")

Any help would be appreciated.

Answer

Kristofersen picture Kristofersen · Feb 16, 2017

You needed to melt your data. I changed your data a little to make it easier to load in, but this should be easy enough to replace.

library(reshape2)
library(scales)
df = data.frame("Year" = seq(2006,2016,by = 1), "Federal" = seq(1,11,by = 1), "Non Federal" = seq(11,1,by = -1))
dfm = melt(df, id.vars = "Year")
ggplot(dfm,aes(x = Year, y = value,fill = variable)) + 
  geom_bar(position = "fill",stat = "identity") + 
  scale_y_continuous(labels = percent_format())

I made some changes to the plot so it's closer to the excel plot. The only thing that is different is the colors.

ggplot(dfm,aes(x = Year, y = value,fill = variable)) + 
  geom_bar(position = "fill",stat = "identity") + 
  scale_y_continuous(labels = percent_format())+ scale_x_continuous(breaks = 2006:2016,labels= as.character(seq(2006,2016,by = 1)))+
  theme(plot.subtitle = element_text(vjust = 1), 
    plot.caption = element_text(vjust = 1), 
    legend.title = element_blank(), 
    axis.title.x=element_blank(),
    axis.title.y=element_blank(),
    legend.position = "bottom", legend.direction = "horizontal")