【问题标题】:Expand plotting area by x-axis to make room for direct labels按 x 轴扩展绘图区域,为直接标签腾出空间
【发布时间】:2014-01-18 19:30:52
【问题描述】:

我正在润色我的图表,但在绘图区域中安装直接标签时遇到了问题。 A 想要移除图形中y1 和左侧 y 轴之间的大部分区域,类似于下面的代码生成的区域,但保留右侧的额外区域以便为标签留出空间。

添加+scale_x_discrete(expand=c(0,0.05)) 会删除两侧的额外区域,但没有为标签留下空间,而且似乎无法仅在一侧删除。

使用+theme(plot.margin = unit(c(0,4,0,0), "cm")) 在绘图区域右侧添加边距仍然不允许标签出现在那里。

将标签放在边框右侧的外部解决方案会更好。

非常感谢任何帮助。

library(ggplot2)
library(directlabels)
library(reshape2)
theme_set(theme_bw())
# some data
dfr<-data.frame(c("Longish Name A","Longish Name B","Longish Name C"),c(1,1,1),c(1,2,3),c(2,3,4)) 
colnames(dfr) <- c("subject","y1","y2","y3")
dfr<-melt(dfr, id.vars="subject")
# the graph
ggplot(data=dfr,aes(y=value, x=variable, group=subject)) +
geom_line(aes(color=subject))+
geom_dl(aes(label=subject), list(dl.trans(x=x+0.2), "last.qp", cex=0.5)) +
guides(color=FALSE)

【问题讨论】:

    标签: r plot ggplot2 axis-labels direct-labels


    【解决方案1】:

    将您的 x 值转换为 aes() 内的数字,然后使用 scale_x_continuous() 返回原始标签并设置一侧更宽的 limits=

    ggplot(data=dfr,aes(y=value, x=as.numeric(variable), group=subject)) +
      geom_line(aes(color=subject))+
      geom_dl(aes(label=subject), list(dl.trans(x=x+0.2), "last.qp", cex=0.5)) +
      guides(color=FALSE)+
      scale_x_continuous(breaks=c(1,2,3),labels=c("y1","y2","y3"),expand=c(0,0.05),
                         limits=c(1,3.4))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多