Rotating and spacing axis labels in ggplot2

I have a plot where the x-axis is a factor whose labels are long. While probably not an ideal visualization, for now I'd like to simply rotate these labels to be vertical. I've figured this part out with the code below, but as you can see, the labels aren't totally visible.

data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
q <- qplot(cut,carat,data=diamonds,geom="boxplot")
q + opts(axis.text.x=theme_text(angle=-90))

在这里输入图像描述


Change the last line to

q + theme(axis.text.x = element_text(angle = 90, hjust = 1))

By default, the axes are aligned at the center of the text, even when rotated. When you rotate +/- 90 degrees, you usually want it to be aligned at the edge instead:

The image above is from this blog post.


要使刻度标签上的文本完全可见并以与y轴标签相同的方向读取,请将最后一行更改为

q + theme(axis.text.x=element_text(angle=90, hjust=1))

Use + coord_flip() .

In "R for Data Science," Wickham and Grolemund speak to this exact problem. In Chapter 3.8, Position Adjustments, they write:

coord_flip() switches the x and y axes. This is useful (for example), if you want horizontal boxplots. It's also useful for long labels: it's hard to get them to fit without overlapping on the x-axis.

Applying this to your plot, we just add + coord_flip() to the ggplot:

data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))

qplot(cut,carat,data = diamonds, geom = "boxplot") +
  coord_flip()

在这里输入图像描述

And now the super long titles are horizontally spread out and very easy to read!

链接地址: http://www.djcxy.com/p/30842.html

上一篇: 如何在ggplot2 R图中设置轴限制?

下一篇: 在ggplot2中旋转和分隔轴标签