我正在利用 ggplot2 中最近添加的辅助轴标签功能。我想仅旋转辅助轴,但无法找到文档或弄清楚如何执行此操作。
使用...旋转所有文本非常简单
ggplot(mtcars, aes(x = wt, y = mpg, colour = mpg)) +
geom_point() +
scale_x_continuous(name = 'Bottom Axis',
sec.axis = sec_axis(trans = ~ .,
name = 'Top Axis',
breaks = c(2:5),
labels = c('Two Two', 'Three Three Three', 'Four Four Four Four', 'Five Five Five Five Five'))) +
## Rotate text of x-axis
theme(axis.text.x = element_text(angle = 90))
我读过的任何文档(例如 scale_continuous 和 themes )都没有提到如何实现仅一个轴的旋转。
我要求这样做的动机是,我希望应用于数据的一些标签在水平放置时很长并且重叠,通过旋转它们我可以避免这种情况,但我希望保留底部轴上的水平方向。
最佳答案
只要您有相对最新版本的ggplot2
,就可以使用axis.text.x.top
:
ggplot(mtcars, aes(x = wt, y = mpg, colour = mpg)) +
geom_point() +
scale_x_continuous(
name = 'Bottom Axis',
sec.axis = sec_axis(
trans = ~ .,
name = 'Top Axis',
breaks = 2:5,
labels = c('Two Two', 'Three Three Three', 'Four Four Four Four', 'Five Five Five Five Five')
)
) +
## Rotate text of x-axis
theme(axis.text.x.top = element_text(angle = 45, hjust = 0))
关于旋转辅助轴标签的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41118517/