Lucca Ramalho
Lucca Ramalho

Reputation: 593

Plot Bar Chart in R - Year issue

I'm working with an shinyapp that creates bar charts according to some user input. Let's say that the user has selected this df

type;year
a;2001
b;2001
a;2002
b;2006
a;2007
b;2007

when i plot the data, it won't show the years 2003to 2005, of course, Because it has no values. So, if i plot them, there will be no gap between these years and it will look wrong.

Any ideas how to set the x-axis value even if it has no data in it?

I've tried to look for something similiar but couldn't find it.

Upvotes: 1

Views: 274

Answers (1)

Prem
Prem

Reputation: 11975

You just need to wrap year column with as.numeric

library(ggplot2)

#sample plot
ggplot(df, aes(x = as.numeric(year), fill = type)) +
  geom_bar()

Output plot is enter image description here

Sample data:

df <- structure(list(type = c("a", "b", "a", "b", "a", "b"), year = c("2001", 
"2001", "2002", "2006", "2007", "2007")), .Names = c("type", 
"year"), row.names = c(NA, -6L), class = "data.frame")

Upvotes: 1

Related Questions