简体   繁体   English

如何使用ggplot2在R中添加大小可变的y轴标签,而又不更改绘图宽度?

[英]How can I add variable size y-axis labels in R with ggplot2 without changing the plot width?

I have a plot I made with ggplot2 in R that I would like to add a horizontal text label to the y-axis. 我有一个用R中的ggplot2绘制的图,我想在y轴上添加水平文本标签。 However, depending on the length of my text, R compresses my plot accordingly to create a fixed width image. 但是,根据我的文本的长度,R会相应压缩我的绘图以创建固定宽度的图像。 However, I need the plots to be identical length and have identical starting and stopping positions (margins) no matter the text width. 但是,无论文本的宽度如何,我都需要图的长度相同,并且起点和终点的位置(边距)相同。

I tried changing the plot margins by overwriting the default ggplot2 theme elements like so: 我试图通过覆盖默认的ggplot2主题元素来更改图边距,如下所示:

library(ggplot2)
png(filename="sample.png", width=5600, height=70)
plot.data <- data.frame(start.points=c(my_start),end.points=c(my_stop))
p <- ggplot(plot.data)
p + geom_rect(aes(xmin=start.points, xmax=end.points, ymin=0, ymax=1), fill="red") + theme_bw() + ylab("sample_title") + 
theme(axis.title.y = element_text(size = 30, colour = "black", angle = 0), axis.text = element_blank(), legend.key = element_blank(), axis.ticks = element_blank(), plot.margin = unit(c(0.1, 0.1, 0.1, 12), "lines"))
dev.off()

So this makes a nice plot, but depending on my axis label the entire plot is stretched or compressed. 因此,这是一个不错的图,但是根据我的轴标签,整个图被拉伸或压缩。 Can someone please help me find a way to hold the plot width and margins static while changing the axis label text? 有人可以帮我找到一种在更改轴标签文本时使打印宽度和边距保持不变的方法吗? If the axis label text is too long and it extends outside of the left-hand image border on into the plot itself, that is ok, as long as the plot doesn't change. 如果轴标签文本太长,并且超出了左侧图像边框的范围,可以进入图本身,只要图不变,就可以。

Thanks for any help! 谢谢你的帮助! I've been banging my head on this for way too long. 我已经为此努力了太久了。

Changing the margins doesn't help in this case because they just add fixed space in addition to your axis label. 在这种情况下,更改边距无济于事,因为它们仅会在轴标签上添加固定的空间。 You could pad your axis label to your expected maximum length to keep the dimensions the same, it's not the most elegant solution but I don't think element_text can do a fixed width at the moment (maybe someone can correct me on this). 您可以将轴标签粘贴到预期的最大长度以保持尺寸不变,这不是最优雅的解决方案,但是我不认为element_text可以固定宽度(也许有人可以对此进行校正)。 Anyways, you could try one of these: 无论如何,您可以尝试以下方法之一:

ylab(sprintf("%40s", "sample_title"))

(padding the axis title to 40 characters with spaces - although total width will still vary depending on your font) (将轴标题用空格填充40个字符-尽管总宽度仍会根据字体而有所不同)

ylab(paste(sprintf("%40s", ""), "\nsample_title\n")

(adding a line of 40 spaces above your axis title and an empty line below - should always give you the same width as long as the axis title isn't longer than that) (在轴标题上方添加40个空格的行,并在其下方添加一个空行-只要轴标题的长度不超过该宽度,就应始终提供相同的宽度)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM