使用ggplot在连续x轴上创建离散仓

时间:2018-09-13 19:51:38

标签: r ggplot2

我发现了类似的问题,但不幸的是没有一个问题帮助我解决了这个问题。

我想使用ggplots根据一个因素替换连续的x轴标签。

在SO的帮助下,下图与我能够得到的非常接近。几乎是正确的,但是我想删除x轴最左侧的零,并将其余标签在x轴的相应容器中居中。

nearly_there

用于生成此代码的代码是:

library(ggplot)

test_base_breaks_x <- function(x){
  b <- pretty(x)
  d <- data.frame(y=-Inf, yend=-Inf, x=min(b), xend=max(b))
  list(geom_segment(data=d, aes(x=x, y=y, xend=xend, yend=yend), inherit.aes=TRUE),
       scale_x_continuous(breaks=c(0,4,8,10), labels =c("0","a","b","c")))
}

test_base_breaks_y <- function(x){
  b <- pretty(x)
  d <- data.frame(x=-Inf, xend=-Inf, y=min(b), yend=max(b))
  list(geom_segment(data=d, aes(x=x, y=y, xend=xend, yend=yend), inherit.aes=TRUE),
       scale_y_continuous(breaks=b))
}


test <- data.frame(names=c("a","a","a","a","b","b","b","b","c","c"),position=c(1,2,3,4,5,6,7,8,9,10),value=c(10,12,14,12,6,7,7,5,18,20))
test_plot <- ggplot(test, aes(position,value))
test_plot <- test_plot +geom_line()
test_plot <- test_plot + test_base_breaks_x(test$position)
test_plot <- test_plot + test_base_breaks_y(test$value)
jpeg("test.jpg")
test_plot
dev.off()

在此先感谢您的帮助!

0 个答案:

没有答案