Fjedsen
Fjedsen

Reputation: 121

Setting x-axis labels in ggplot2 to original input

I am relativley new to ggplot and encountered a problem I've never had before: I have a dataset with values for different years. The problem is the gap between the years is not constant (1993, 1995, 2000, 2005, 2010, 2014). When I plot the whole thing I get this (of course): logic but unwanted x-acis scaling

I can't think of a way to get a constant distance between the bar groups and have the original years on the axis.

Do you have any hints?

Upvotes: 0

Views: 268

Answers (2)

eipi10
eipi10

Reputation: 93811

Instead of distorting the time relationships by enforcing the same distance between each bar group, you could use a line plot. This makes it easier to see trends and compare groups and also avoids distorting the time scale:

library(ggplot2)

# Fake data
set.seed(115)
dat = data.frame(auto=rnorm(18,200,50), year=rep(c(1993,seq(1995,2010,5),2014), each=3),
                 group=rep(c("A","B","C"),6))

pd = position_dodge(0.8)

ggplot(dat, aes(year, auto, color=group)) +
  geom_line(position=pd) +
  geom_point(position=pd) +
  scale_y_continuous(limits=c(0,max(dat$auto))) +
  scale_x_continuous(minor_breaks=1993:2016) +
  theme_bw()

enter image description here

Upvotes: 0

prateek1592
prateek1592

Reputation: 547

This should do the work

library(ggplot2)

set.seed(10)
y <- sample(1990:2015,5)
data <- data.frame(expand.grid(Year=y, tag=c("a","b","c")))

data$value <- rnorm(nrow(data))*10 + 50
data$Year <- as.factor(data$Year)

ggplot(data, aes(x=Year,y=value)) + 
  geom_bar(stat = "identity",aes(fill=tag), position="dodge")

enter image description here

Upvotes: 1

Related Questions