Ggplot: Multi variable.

The data that is inferred from the larger using data dplyr

shows me the total sales of the four quarters for 2013 and 2014.

    Quarter  X2013       X2014    Total.Result
1   Qtr 1   77282.13    66421.10    143703.2
2   Qtr 2   69174.64    76480.13    145654.8
3   Qtr 3   65238.47    79081.74    144320.2
4   Qtr 4   65429.73    109738.82   175168.5

      

I want to plot a chart for the next use ggplot

by comparing two years on bars and for such groups of bars for each of the quarters as shown below. (output from MS Excel)

enter image description here

The ggplot operator I used is shown below (I could be wrong)

ggplot(qtr2, aes(x=as.factor(Quarter),fill=c(X2013,X2014))) +
    geom_bar(position="dodge")

      

and I get the error

Error: Aesthetics must either be length one, or the same length as the dataProblems:as.factor(Quarter)

      

+1


source to share


1 answer


You need to cast your data into long format for ggplot:

require(ggplot2)
require(reshape2)
df <- read.table(header = TRUE, text = 'R    Quarter  X2013       X2014    Total.Result
1   Qtr 1   77282.13    66421.10    143703.2
2   Qtr 2   69174.64    76480.13    145654.8
3   Qtr 3   65238.47    79081.74    144320.2
4   Qtr 4   65429.73    109738.82   175168.5')
df$R <- NULL
head(df)

# bring to long data (1)
dfm <- melt(df, id.vars = c('Quarter', 'Total.Result'))
dfm


ggplot(dfm, aes(x = factor(Quarter), y = value, fill = variable) ) +
  geom_bar(stat="identity", position = 'dodge')

      



Regarding the column / column of the grand total: I don't know where this data should come from (missing?). Is there only one column but two columns? And the meanings don't fit. If you tell me how to create them, it shouldn't be a problem to build.

+5


source







All Articles