首页 > 解决方案 > 在 R 中的一般主题()中为 axis.text.x 设置条件

问题描述

我正在为一个包括许多不同类型的情节的大型项目创建一个统一的主题。我设置了一个整体主题,其中axis.text.x.bottom 的角度为0(水平),但是我的一些x 轴标签很长。对于长度小于 3 的标签,我想将 axis.text.x.bottom 的角度设置为 0,对于长度大于 3 的标签,我想将其设置为 90(从下到上阅读),而无需指定主题每个单独的情节。

*** 这是一个高度简化的例子

library(ggplot2)
report_theme(axis.text.x.bottom = element_text(angle = 0))

testdata1 = matrix(NA, nrow = 10, ncol = 2)
testdata1[,1] = 1:10
testdata1[,2] = 1:10

testdata1 = as.data.frame(testdata1)

g1 = ggplot(testdata1, aes(x = testdata1[,1], y = testdata1[,2])) + geom_point()
g1 + report_theme


testdata2 = testdata1
testdata2[,1] = c("number 1", "number 2", "number 3", "number 4", "number 5", "number 6", "number 7", "number 8", "number 9", "number 10")

g2 = ggplot(testdata, aes(x = testdata2[,1], y = testdata2[,2])) + geom_point()
g2 + report_theme

testdata1 绘图

测试数据 2 绘图

testdata1 的绘图看起来不错,因为 x 轴标签是数字,但是 testdata2 的 x 轴标签是长字符串,因此由于它们重叠,因此不容易水平读取。

我知道如何单独更改每个绘图的角度,但它需要知道用于绘图的数据框的名称,并且我希望能够在整个主题 report_theme 中做到这一点。当每个绘图使用不同的数据框时,我该怎么做?

标签: rggplot2themes

解决方案


推荐阅读