绘图区域外的直接标签/禁用直接标签的自动调整大小

时间:2012-12-12 14:45:07

标签: r ggplot2 labels

默认情况下,'directlabels'包显然会尝试通过减少标签字体大小来使每个标签适合正常的绘图区域。

下面,Label for OneLabel for TwoLabel for Threeeeeeeeee都应该具有相同的字体大小,如果标签用完绘图区域就可以了(因为clip是禁用自定义注释以显示)。

事实上,我可能想要设置xlim=c(1,3),标签应该完全在绘图区域之外。以下图片左侧列为xlim=c(1,3.4),右侧列为xlim=c(1,3)

我了解到cex可用于重置标签的fontsize,但它似乎与包的标签分离算法冲突。下面的第一行图片是cexcex=1的最后一行。

很高兴找到一种方法让标签不重叠,字体大小相同,并且适用于xlim=c(1,3)xlim=c(1,3.4)

enter image description here

library(reshape)
library(ggplot2)
library(directlabels)

df=data.frame(
  x = 1:3,
  One=c(12, 8, 13),
  Two=c(13, 7, 11),
  Threeeeeeeeee=c(11, 9, 11))

df.d.melt = melt(df[,c("x","One","Two","Threeeeeeeeee")], id.vars="x")
df.d.melt$variable1 = df.d.melt$variable
levels(df.d.melt$variable1) = paste("","Lable for",levels(df.d.melt$variable1))

p = ggplot(df.d.melt, aes(x=x, y=value, color=variable)) + 
  geom_line(size=1.1) +
  geom_text(aes(x =3.4, y=8, label="Custom Outside\nChart Annotation"), show_guide=FALSE) + 
  coord_cartesian(xlim=c(1,3.4)) +
  geom_dl(aes(label=variable1), method=list("last.qp", cex=1), show_guide=FALSE) + 
  theme(legend.position="top",plot.margin = unit(c(0, 4, 0, 0), "cm")) 

p1 <- ggplot_gtable(ggplot_build(p))
p1$layout$clip[p1$layout$name=="panel"] <- "off"
grid.draw(p1)

2 个答案:

答案 0 :(得分:1)

默认情况下,directlabels假设您希望在绘图区域内有可读标签,因此它会缩小文本大小,以便使用reduce.cex.lr使标签适合内部。可以通过定义不减小文本大小的自定义定位方法来完成绘图外的标签,例如

do.not.reduce <-
  list(cex=2, "last.points", "calc.boxes",
       qp.labels("y", "bottom", "top", make.tiebreaker("x", "y")))

WithLegend <- ggplot(df.d.melt, aes(x=x, y=value, color=variable)) + 
  geom_line(size=1.1) +
  geom_text(aes(x =3.4, y=8, label="Custom Outside\nChart Annotation")) + 
  coord_cartesian(xlim=c(1,3)) +
  theme(plot.margin = unit(c(0, 4, 0, 0), "cm"))
WithLabels <- direct.label(WithLegend, "do.not.reduce")
GTable <- ggplot_gtable(ggplot_build(WithLabels))
GTable$layout$clip[GTable$layout$name=="panel"] <- "off"
grid.draw(GTable)

答案 1 :(得分:0)

一个可行的解决方案是将标签附加到图表左侧的其他不可见的短线(例如,在x=1x=1.001上定义)并使用直接标签'trans_new来将注释移动到所需的x值。