简体   繁体   English

如何旋转 ggplot2 中的轴标签?

[英]How to rotate the axis labels in ggplot2?

I have the following graph that I generated using ggplot2我有使用 ggplot2 生成的下图在此处输入图像描述

I had finalPlot as the ggplot object. To add labels I used我将finalPlot作为 ggplot object。要添加我使用的标签

finalPlot + stat_bin() + scale_x_continuous('Solution Cost') + scale_y_continuous('Number of Solutions')`

How can I change the orientation of the y axis label to make it appear horizontal and if possible span it across two lines like我怎样才能改变 y 轴 label 的方向,让它看起来水平,如果可能的话,跨越两条线,比如

Number of
Solutions

The syntax has changed in recent versions of ggplot2;语法在 ggplot2 的最新版本中发生了变化; if you try the above answer, you'll get如果你尝试上面的答案,你会得到

Error: Use 'theme' instead.错误:改用“主题”。 (Defunct; last used in version 0.9.1) (已停用;最后一次使用是在版本 0.9.1 中)

These days you should use这些天你应该使用

finalPlot + ylab("Number of\nSolutions") + theme(axis.title.y = element_text(angle=0))

For the rotation angle of the axis text you need to use element_text() .对于轴文本的旋转角度,您需要使用element_text() See this post on SO for some examples.有关一些示例,请参阅关于 SO 的这篇文章 For spacing over two lines I would add a "\n" on the location in the string where you want to put the newline.对于超过两行的间距,我会在字符串中要放置换行符的位置添加一个"\n"

This will set the correct orientation for the y axis text and force a line break:这将为 y 轴文本设置正确的方向并强制换行:

finalPlot + ylab("Number of\nSolutions") + 
    theme(axis.title.y = element_text(angle = 0))

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

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