1

I have a following data frame, called st_data:

enter image description here

I am interested in drawing value vs year plot, for each person. So following code generates a graph:

ggplot(st_data, aes(x = year, y = value)) 
+ geom_bar(stat = "identity", aes(fill = person), position = "dodge") 
+ theme(axis.text.x = element_text(angle = 45, hjust = 1))

Graph:

enter image description here

However, as you can see, it also considered year axis in decimals. So I realized, as its a int values, may be thats why. So I converted year column to Date type by following:

st_data$year<- as.Date(as.character(st_data$year), format('%Y'))

It also introduced a default month and date also. So year 2008 changed to 28-05-2008. Now the same code gave following graph:

enter image description here

Better than earlier, however the year vector has only 4 possible values viz. 1999, 2002, 2005, and 2008. So I want only these 4 years on the x-axis. How to achieve this?

I have also used scale_x_date, but no luck.

ggplot(st_data, aes(x = year, y = value)) 
+ geom_bar(stat = "identity", aes(fill = person), position = "dodge") 
+ scale_x_date(labels = date_format("%Y"))

It generates same graph as earlier one. So how do I get only 4 years on x-axis and they should be any possible values of year vector viz. 1999, 2002, 2005, and 2008.

1 Answer 1

1

In this case you don't really want to treat your year values as years. You want to treat them like a categorical variable. So don't do the st_data$year=as.Date stuff. But make sure year is a factor

#sample data
st_data <- data.frame(
    person=factor(rep(c("06037","24510"), each=4)),
    year=rep(c(1999,2002,2005,2008), 2),
    value=c(runif(4,1000,2000), runif(4, 0,500))
)

#convert year to factor
st_data$year = factor(st_data$year)

Just use

ggplot(st_data, aes(x = year, y = value)) + 
    geom_bar(stat = "identity", aes(fill = person), position = "dodge") 

to get

sample bar plot

2
  • when I ran the same sample set you gave, I got the correct graph. But with my sample data, I am getting same as i.stack.imgur.com/aSRG5.png What could be the problem?
    – avi
    May 25, 2014 at 16:08
  • @avi oops, i forgot to make it clear that year should be a factor. I will edit.
    – MrFlick
    May 25, 2014 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.