Reputation: 768
I have a data which shows total sales in the years 2013 and 2014.
yr_sales
Year sum_amount
1 2013 277125.0
2 2014 331721.8
I wish to draw a barplot with Year on X and sales on Y axis.
ggplot(yr_sales, aes(x=Year, y=sum_amount)) +
geom_bar(stat="identity", fill="lightblue", colour="black")
But all I get is a messed up X axis :
My expected output is (as I got in MS Excel)
Upvotes: 2
Views: 148
Reputation: 768
Using the answer given by @slhck I did the below thing :
ggplot(yr_sales, aes(x=as.factor(Year), y=sum_amount,width=0.4)) +
geom_bar(stat="identity", fill="blue", colour="black")
And my output is perfect..
Upvotes: 0
Reputation: 38652
Your year is treated as a numerical variable. The way you want to display your data requires it to be a factor (i.e., it has discrete values and there cannot be a year 2013.5
).
Set as.factor(Year)
for the aesthetic mapping of your x axis:
ggplot(yr_sales, aes(x=as.factor(Year), y=sum_amount)) +
geom_bar(stat="identity", fill="lightblue", colour="black")
You could also change the data itself, but this could cause issues when you want your year as an actual numerical variable:
yr_sales$Year = as.factor(yr_sales$Year)
If you did the above, you would not need to use as.factor
in the aesthetic mapping.
Upvotes: 2