R stacked barchart with aggregate data

后端 未结 2 1251
我寻月下人不归
我寻月下人不归 2021-01-02 16:56

I\'m having troubles creating a stacked barchart with aggregate data. When dealing with aggregate tables from other people\'s reports I generally use Excel, but I\'d like to

相关标签:
2条回答
  • 2021-01-02 17:26

    reshape your data:

    library(reshape2)
    df <- melt(D)
    

    And simply plot it :)

    ggplot(df, aes(x = factor(Education), y = value, fill = factor(variable))) +
    geom_bar() + facet_grid(.~Group) +
    ylab('') + xlab('') + opts(title = '') + scale_fill_discrete('') +
    theme_bw() +
    opts(axis.text.x=theme_text(angle = 45, hjust = 1, vjust = 1))
    

    Where the first line creates sets aesthetics, second line adds bar layer and the facet, on the 3rd line we remove unwanted texts from the plot, the 4th line sets the b&w theme and on the last line we rotate the x asis labels.

    enter image description here

    0 讨论(0)
  • 2021-01-02 17:40

    The trick is to use melt from the plyr packate to melt down the three measured columns into one (a new column named value), along with an identifying column (named variable) to group on:

    require(ggplot2)
    require(reshape)
    
    # first we need to get Full.Time, PT.16, etc. into one column
    df <- melt(D, .measure.vars=.(Full.Time, PT.16.hours, PT.16.hours.1))
    ggplot(df, aes(x=Education, y=value, fill=variable )) +
      geom_bar(stat="identity")
    

    The rest is just reordering factors so output matches what you want.

    Take a look at df to see what melt ends up doing, since its a common workflow for ggplot2.

    plot

    To move on to a facetted plot using the Group factor just requires adding the appropriate facet_wrap:

    ggplot(df, aes(x=Education, y=value, fill=variable )) +
      geom_bar(stat="identity") +
      facet_wrap(~ Group)
    

    facetted plot

    0 讨论(0)
提交回复
热议问题