2016-08-22 135 views
4

我做了Excel中的以下情节:与刻度标记一起移动x或y轴单ggplot中间(无面)

enter image description here

但后来我想我会让它更漂亮的使用ggplot。我能走到今天:

enter image description here

如果你好奇,该数据是根据我answer here,但它其实并不重要。这个图是一个标准的ggplot2构造,有一些偏爱,并且通过中间的x轴的粗线是通过p + geom_hline(aes(yintercept=0))p是ggplot对象)实现的。

我觉得Excel绘图中的轴配置更好。它强调0行(当数据是钱时很重要)并且发现拦截更容易,因为您不必在底部追踪行。这也是人们在纸或纸板上绘图时如何绘制轴线的方式。

在ggplot中轴也可以像这样移动吗?我不仅需要线路,还要移动刻度线标签。如果是,如何?如果不是,是技术还是设计的原因?如果通过设计,为什么做出这个决定?

+3

你可以伪造它与'geom_hline','geom_text'和'geom_segment' 。另外,如果我需要7亿美元退休,我现在应该放弃。 – alistaire

+1

但看看它花多快。全部都过去了70年。相当退休。 – shayaa

+1

只需写你自己的美元价值适当的主题或看到这里。 http://stackoverflow.com/questions/21026598/ggplot2-adding-secondary-transformed-x-axis-on-top-of-plot – shayaa

回答

3

我试图改变主题的axis.text.x,但只能改变hjust。
所以我认为你可以删除axis.text.x,然后使用geom_text()来添加。
例如:

test <- data.frame(x=seq(1,5), y=seq(-1,3)) 
ggplot(data=test, aes(x,y)) + 
    geom_line() + 
    theme(axis.text.x=element_blank(), axis.ticks.x=element_blank()) + 
    geom_text(data=data.frame(x=seq(1,5), y=rep(0,5)), label=seq(1,5), vjust=1.5) 

也许这些代码是有用的。

enter image description here

7

试试这个,

shift_axis <- function(p, y=0){ 
    g <- ggplotGrob(p) 
    dummy <- data.frame(y=y) 
    ax <- g[["grobs"]][g$layout$name == "axis-b"][[1]] 
    p + annotation_custom(grid::grobTree(ax, vp = grid::viewport(y=1, height=sum(ax$height))), 
         ymax=y, ymin=y) + 
    geom_hline(aes(yintercept=y), data = dummy) + 
    theme(axis.text.x = element_blank(), 
      axis.ticks.x=element_blank()) 

} 

p <- qplot(1:10, 1:10) + theme_bw() 
shift_axis(p, 5) 

enter image description here

+0

这太棒了:) – Veera

-3

由于alistaire评论它可以使用geom_hlinegeom_text如下图所示进行。

df <- data.frame(YearMonth = c(200606,200606,200608,200701,200703,200605), 
      person1 = c('Alice','Bob','Alice','Alice','Bob','Alice'), 
      person2 = c('Bob','Alice','Bob','Bob','Alice','Bob'), 
      Event = c('event1','event2','event3','event3','event2','event4') 
) 

df$YM <- as.Date(paste0("01",df$YearMonth), format="%d%Y%m") 
rangeYM <- range(df$YM) 

ggplot()+geom_blank(aes(x= rangeYM, y = c(-1,1))) + labs(x = "", y = "") + 
theme(axis.ticks = element_blank()) + 
geom_hline(yintercept = 0, col = 'maroon') + 
scale_x_date(date_labels = '%b-%y', date_breaks = "month", minor_breaks = NULL) + 
scale_y_continuous(minor_breaks = NULL) + 
geom_text(aes(x = df$YM, y = 0, label = paste(format(df$YM, "%b-%y")), vjust = 1.5), colour = "#5B7FA3", size = 3.5, fontface = "bold") 

enter image description here

0

只是为了完成巴蒂斯特与等效的出色答卷用于移动Y轴:

shift_axis_x <- function(p, x=0){ 
     g <- ggplotGrob(p) 
     dummy <- data.frame(x=x) 
     ax <- g[["grobs"]][g$layout$name == "axis-l"][[1]] 
     p + annotation_custom(grid::grobTree(ax, vp = grid::viewport(x=1, width = sum(ax$height))), 
          xmax=x, xmin=x) + 
     geom_vline(aes(xintercept=x), data = dummy) + 
     theme(axis.text.y = element_blank(), 
       axis.ticks.y=element_blank()) 
    }