R ggplot2 Bar Chart on Multiple Columns

2020-04-20 11:56发布

问题:

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.

回答1:

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)



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



标签: r ggplot2