Reputation: 2478
I am a beginner in R and am dealing with some data as follows-
Month <- 1 2 3 4 5 6 7 8 9 10 11 12
Sales <- 50 60 80 50 40 30 35 55 70 60 50 40
I have to plot these data using the plot() function which I am able to do by doing certain edits to it as follows-
plot(Month, Coffee, type='l', ylim=c(0, 100))
abline(h=max(Coffee), col='red')
The new requirement is to plot the names of 'Month' which is in X-axis as actual month names viz., January, February, March,....., December.
I tried to do that using-
n_month <- format(ISOdate(2017,1:12,1),"%B")
plot(n_month, Coffee, type='l', ylim=c(0, 100))
plot(n_month, Coffee, type='l', ylim=c(0, 100), xlim=(1, 12))
I also tried the following-
# 'xaxt' to suppress labels on x-axis
plot(Month, Coffee, ylim=c(0,100), xlab="Month", ylab="Coffee", xaxt="n", type='l')
# 'axis' to add in my own labels
axis(1, at=1:12, labels=month.name)
However, the final graph does not mention all the names but rather certain names like- January, March, May, June, July, September & November.
Any suggestions as to how I can get the names of all 12 months on X-axis?
Thanks!
Upvotes: 3
Views: 19021
Reputation: 2478
I solved it using-
axis(1, at=1:12, labels=month.name, cex.axis=0.5)
The 'cex.axis' argument did the trick of adjusting all month names on the X-axis.
Upvotes: 6
Reputation: 11659
I hope it works for u
month <- c("Jan", "Feb", "Mar",
"Apr", "May", "Jun",
"Jul", "Agu","Sep",
"Oce", "Nov", "Dec")
sales <- c(50, 60, 80, 50, 40, 30, 35, 55, 70, 60, 50, 40)
dt<-data.frame( Month<-month, Sales=sales )
library(ggplot2)
ggplot(dt ,aes( Month,Sales)) +
geom_bar(stat="identity",aes(fill = "Month"), data =dt , alpha = 0.5 )
Just make sure u have ggplot2
in ur system
At the end it would be like this:
Upvotes: 2