在左侧的线条末端绘制标签

时间:2017-09-01 07:48:22

标签: r ggplot2

此问题基于此answer,它为右侧提供了解决方案。

我需要将标签切换到另一侧,因为我的曲线合并,但是尽管有“关闭裁剪的代码”,它们仍会被剪裁。 enter image description here (抱歉填充,这是控制宽高比的意外后果。)

以下是图表的代码:

library(ggplot2)
p <- ggplot(temp, aes(x=year, y=value/10^6, group=variable)) + geom_point(shape=1, size=2) + geom_line(size=1) + 
  geom_text(data=temp[temp$year==min(temp$year),], aes(label=c("MSA 2012", "MSA en cours"), x=year-.25, y=value/10^6), 
            hjust = 1, size=4.6) + 
  scale_x_continuous(breaks=seq(2001,2015,2)) + scale_y_continuous(breaks=seq(95,105,5), position="right") + 
  labs(x="Année", y="Emploi (millions)") + 
  theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank(), panel.background=element_blank(), 
        axis.line = element_line(colour = "black"), legend.position="top", legend.direction="horizontal", 
        axis.text = element_text(color="black", size=13), axis.title = element_text(color="black", size=13),
        aspect.ratio=.25)
# Code to turn off clipping
library(grid)
gt <- ggplotGrob(p)
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)

1 个答案:

答案 0 :(得分:2)

一个简单的解决方案是修改与p图关联的gtable的布局。

# Generate a toy dataset
set.seed(123)
temp = data.frame(year=rep(2001:2015,2), value=cumsum(rnorm(30)), variable=rep(c("A","B"),each=15))
library(scales)
temp$value <- rescale(temp$value, to=c(95*10^6,105*10^6))  


library(ggplot2)
p <- ggplot(temp, aes(x=year, y=value/10^6, group=variable)) + geom_point(shape=1, size=2) + geom_line(size=1) + 
  geom_text(data=temp[temp$year==min(temp$year),], aes(label=c("MSA 2012", "MSA en cours"), x=year-.25, y=value/10^6), 
            hjust = 1, size=4.6) + 
  scale_x_continuous(breaks=seq(2001,2015,2)) + scale_y_continuous(breaks=seq(95,105,5), position="right") + 
  labs(x="Année", y="Emploi (millions)") + 
  theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank(), panel.background=element_blank(), 
        axis.line = element_line(colour = "black"), legend.position="top", legend.direction="horizontal", 
        axis.text = element_text(color="black", size=13), axis.title = element_text(color="black", size=13),
        aspect.ratio=.25)

library(grid)
gt <- ggplotGrob(p)
### Modify the layout of the gtable
gt$widths[[2]] <- unit(2.5, "cm")
###
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)

enter image description here