1

This seems so simple, but there is something fundamental I am not getting here. I have a dataframe with counts of some event per month as columns, per year as rows. Like this:

season  sep oct nov dec jan feb
2000    2   7   47  152 259 140
2001    1   5   88  236 251 145
2002    2   14  72  263 331 147
2003    5   6   71  207 290 242

First, I would like to create a bar chart for one season. For example, for the 2000 season, a bar chart showing the values for each month as a vertical bar (alas, not enough rep points to post an image of an example). I'm guessing I need to reshape my data in some way?

Ultimately I would like to create a facet wrapped set of charts, one for each season.

Please note I found a similar post, but the post was over complicated due to a lack of clarity on the question.

2
  • 1
    here is one stackoverflow.com/questions/16761329/… Commented Apr 11, 2015 at 14:14
  • 1
    @user20650 - yes, thank you. See my comment below. My lack of fundamentals and understanding melt is my problem here. Commented Apr 11, 2015 at 14:21

2 Answers 2

5
library(reshape2)
library(ggplot2)
df_m <- melt(df, id.vars = "season")

In order to plot for one season (e.g. 2000)

ggplot(subset(df_m, season == "2001"), aes(x = variable, y = value)) +
geom_bar(stat = "identity")

And for facet wrapped set of charts try:

ggplot(df_m, aes(x = variable, y = value)) + geom_bar(stat = "identity") +
facet_wrap(~season)

enter image description here

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

2 Comments

Thank you very much @RStudent. From my perspective you should change your name to RMaster! FYI, I am quite new at this and felt I needed to pay more attention to first understanding vectors, lists, arrays and data frames, but graphs are so much fun. Ultimately I jumped ahead, but your demonstration of melt helped me understand I need to go back to fundamentals. I want to really understand the how/why here.
Thank you a lot @DatamineR! Very useful "melt" function
2

Here's a tidyr/dplyr approach:

if (!require("pacman")) install.packages("pacman")
pacman::p_load(dplyr, tidyr, ggplot2)

dat %>%
    gather(month, value, -season) %>%
    ggplot(aes(y = value, x = month)) +
    geom_bar(stat = "identity") +
    facet_wrap(~season)

enter image description here

1 Comment

I like that. Thanks. I have been reading about dplyr and it seems much more accessible to me. For kicks I would like to plot all fours years, in order by month on one chart, but I won't ask - I will try and figure this out. I find learning R is best when it is with data that I am actually familiar with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.