3

I'd like to create a stacked bar graph of my data frame df without having to transform the data, for interpretability reasons. My data looks like this:

#Code year <- c(1:5) burglaries <- c(234,211,201,150,155) robberies <- c(12, 19,18,23,25) total <- burglaries + robberies df <- data.frame(year, burglaries, robberies, total) #Output print(df) year burglaries robberies total 1 1 234 12 246 2 2 211 19 230 3 3 201 18 219 4 4 150 23 173 5 5 155 25 180 

I can create the plot I need by transforming my data set as follows:

df2 <- rbind( data.frame(year, "count" = burglaries, "type"="burglaries"), data.frame(year, "count" = robberies, "type"="robberies") ) ggplot(df2, aes(x=year, y=count, fill=type)) + geom_bar(stat="identity") 

enter image description here

Is there a way to create the same plot with the data frame df? Although I could transform the data, I worry it'll make it harder to follow what's happening in the program and catch errors (the data set I'm using is quite large).

1
  • 1
    You're working against the way ggplot was specifically designed to be used. ggplot wants you to transform (melt, gather, tidy, whatever you want to call it) your data first. So the short answer is no, not really. Commented Dec 1, 2016 at 17:21

2 Answers 2

3

I did some additional research and found the plot_ly() function from the library plotly allows you to do just that. Here's the link for more info: plotly website

plot_ly(data=df, x = ~year, y = ~burglaries, type = 'bar', name = 'Burglaries') %>% add_trace(y = ~robberies, name = 'Robberies') %>% layout(yaxis = list(title = 'Count'), barmode = 'stack') 

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

2

Ultimately a transformation is required but a more elegant way is to use tidyr:

df %>% select(-total) %>% gather(type, count, burglaries:robberies) %>% ggplot(., aes(x=year, y=count, fill=forcats::fct_rev(type))) + geom_bar(stat="identity") 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.