Reputation: 768
A data that is deduced from a larger data using dplyr
, shows me information regarding the total sales of the four quarters for the years 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 wish to plot a bargraph for the following using ggplot
by comparing the two years on the bars and for such bar-groups for the each of the quarters like shown below. (output from MS Excel)
The ggplot statement that I used is as shown below (I may be wrong)
ggplot(qtr2, aes(x=as.factor(Quarter),fill=c(X2013,X2014))) +
geom_bar(position="dodge")
and I get an error
Error: Aesthetics must either be length one, or the same length as the dataProblems:as.factor(Quarter)
Upvotes: 1
Views: 5425
Reputation: 13280
You need to bring your data into the 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 Total Result column / bars: I don't know where this data should come from (missing?) - There is only one column, but two bars? And the values do not fit. If you tell me how to generate these, it should be no problem to plot.
Upvotes: 5