【问题标题】:ggplot2 stagger axis labelsggplot2交错轴标签
【发布时间】:2015-11-04 18:14:21
【问题描述】:

我正在制作一个 ggplot。 x 轴是因子,标签很长。

我无法缩短标签,它们尽可能短。

我有兴趣使标签垂直偏移。我的偏好是将每个奇数标签放在高度 0 处,每个偶数标签放在离 x 轴更远 2 个单位的高度处。

我看过这里,ggplot-hopeful-help,但在解释发生的事情时确实遇到了麻烦,因此无法制作出有用的版本。

有什么想法吗??

(下面的示例代码...我在这里不太擅长格式化代码,看来...sry。)

library("ggplot2"); 
stack <- data.frame(value =rnorm(n = 1000, sd = 2, mean=34)); stack$fact <- as.factor(rep(1:5, each=1000/5));
ggplot(stack, aes(x=fact, y=value)) + geom_boxplot(aes(fill=fact))+ scale_x_discrete(breaks=c("1", "2", "3", "4", "5"), labels=c("hi","don't suggest I shorten the text","I need long labels", "This is a long factor label","This label is very long"))

【问题讨论】:

  • 您所指的答案,为您提供您正在寻找的解决方案。对于您的情况,它将是 + theme(axis.text.x = element_text(vjust = grid::unit(c(-2, 0), "points"))),其中 -2 表示奇数标签,0 表示偶数标签。

标签: r ggplot2 axis-labels


【解决方案1】:

不管你是否理解,它似乎工作得很好。在您的问题中调用情节your_plot:

your_plot + theme(axis.text.x = element_text(vjust = grid::unit(c(-2, 0, 2), "points")))

在theme() 中指定首选项是调整ggplot 陷阱的方法。 axis.text.x 仅修改 x 轴文本,该文本是使用 element_text() 设置的首选项创建的。您可以在element_text() 中指定字体大小、字体系列、旋转角度等。 vjust 代表“垂直对齐”,因此将 vjust 设置为三个值,-2、0 和 2 会将这些值应用于连续的 x 轴标签。 (显然负数上升了,这让我很惊讶。)

使用grid::unit() 允许我们指定文本垂直移动的单位(在本例中为点)。查看?grid::units 表明您可以使用英寸、厘米或其他几个单位。

唯一的问题是与 x 轴标题重叠。我认为解决这个问题的最简单方法是在它之前添加几个换行符"\n":

your_plot + 
    theme(axis.text.x = element_text(vjust = grid::unit(c(-2, 0, 2), "points"))) +
    labs(x = "\n\nfact")

另一种解决方案是旋转文本:

your_plot + theme(axis.text.x = element_text(angle = -90, hjust = 0, vjust = 0))

更多阅读,there's a whole vignette on ggplot2 theming。

【讨论】:

  • 完美。我将整个对象包裹在 pdf() 中,所以对我有用的最终配置是:'pdf("my.file.pdf") my.plot + theme(axis.text.x = element_text(vjust = grid: :unit(c(-2, -0.1, 1.2), "points"))) dev.off()
  • 在使用 ggplots 时,我通常建议使用 ggsave() 而不是 pdf()... dev.off()。
【解决方案2】:
stack <- data.frame(value =rnorm(n = 1000, sd = 2, mean=34))
stack$fact <- as.factor(rep(1:5, each=1000/5))

ggplot(stack, aes(x=fact, y=value)) + 
geom_boxplot(aes(fill=fact)) + 
scale_x_discrete(breaks=c("1", "2", "3", "4", "5"), labels=c("hi","don't suggest I shorten the text","I need long labels", "This is a long factor label","This label is very long"))+
theme(axis.text.x = element_text(vjust = grid::unit(c(0, 2), "points"))) + 
theme(axis.title.x = element_text(vjust = -0.6))

实际上the link you reported 中讨论的解决方案只需要稍作修改。 我也加了

theme(axis.title.x = element_text(vjust = -0.6)) 

降低 x 轴标签以防止重叠。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多