简体   繁体   中英

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): 逻辑,但不需要x-acis缩放

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?

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")

在此处输入图片说明

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()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM