本文介绍了在ggplot中添加换行符到轴标签和刻度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在寻找一种在绘图的x轴上使用长变量名的方法。当然,我可以使用较小的字体或将它们旋转一点,但我想让它们保持垂直和可读性。 举个例子: df df_M plot $ / b $ p 这里x轴只是字母,但如果我想使用全名,名字使用不成比例的空间: plot + theme(axis.text.x = element_text(angle = 90))+ scale_x_discrete (break = unique(df_M $ variable),labels = c(Ambystoma mexicanum,Daubentonia madagascariensis,Psychrolutes marcidus)) 所以我想在标签中加一个换行符,最好在ggplot2中,但当然欢迎其他解决方案。 谢谢! 解决方案您可以添加自己的格式程序(请参阅 scales 例子) addline_format< - function(x,...){ gsub('\\'','\\\',x)} myplot + scale_x_discrete(breaks = unique(df_M $ variable) , labels = addline_format(c(Ambystoma mexicanum,Daubentonia madagascariensis,Psychrolutes marcidus))) 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. As an example: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")plothere 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"))So I would like to put a line break in the labels. Preferably in ggplot2 but other solutions are welcome of course.Thanks! 解决方案 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','\n',x)}myplot + scale_x_discrete(breaks=unique(df_M$variable), labels=addline_format(c("Ambystoma mexicanum", "Daubentonia madagascariensis", "Psychrolutes marcidus"))) 这篇关于在ggplot中添加换行符到轴标签和刻度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-16 16:37