在 ggplot 中为轴标签和刻度添加换行符 [英] Add line break to axis labels and ticks in ggplot
问题描述
我正在寻找一种在绘图的 x 轴上使用长变量名称的方法.当然,我可以使用较小的字体或稍微旋转它们,但我希望它们保持垂直和可读性.
I'm looking for a way to use long variable names on the x axis of a plot. Of course I could use a smaller font or rotate them a little but I would like keep them vertical and readable.
举个例子:
df <- data.frame(a=LETTERS[1:20], b=rnorm(20), c=rnorm(20), d=rnorm(20))
df_M <- melt(df, id="a")
plot <- ggplot(data=df_M,
aes(x=variable, y=a, fill=value)) +
geom_tile() +
scale_fill_gradient(low="green", high="red")
plot
这里的 x 轴只是字母,但如果我想使用全名,名称会使用不成比例的空间:
here the x axis is just letters, but if I want to use the full name, the names use a disproportionate amount of space:
plot +
theme(axis.text.x=element_text(angle=90)) +
scale_x_discrete(breaks=unique(df_M$variable),
labels=c("Ambystoma mexicanum",
"Daubentonia madagascariensis",
"Psychrolutes marcidus"))
所以我想在标签中换行.最好在 ggplot2 中,但当然也欢迎其他解决方案.
So I would like to put a line break in the labels. Preferably in ggplot2 but other solutions are welcome of course.
谢谢!
推荐答案
您可以添加自己的格式化程序(更多示例请参见 scales
包).在这里,我用新行替换 x 标签中的任何空格.
You can add your own formatter ( see scales
package for more examples). Here I replace any space in your x labels by a new line.
addline_format <- function(x,...){
gsub('\s','
',x)
}
myplot +
scale_x_discrete(breaks=unique(df_M$variable),
labels=addline_format(c("Ambystoma mexicanum",
"Daubentonia madagascariensis", "Psychrolutes marcidus")))
这篇关于在 ggplot 中为轴标签和刻度添加换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!