我正在寻找一种在绘图的x轴上使用长变量名的方法。当然,我可以使用较小的字体或将它们旋转一些,但我想让它们保持垂直和易读。
作为一个例子:
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轴只是字母,但如果我想使用全名,名称会占用不成比例的空间:
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,当然也欢迎其他解决方案。
谢谢!
addline_format
函数。难道不能直接在标签中指定换行吗?例如:c("Ambystoma\nmexicanum",...
- Fuhrmanatorscale_x_discrete(labels=function(x){sub("\\s", "\n", x)})
。该代码的作用是将x轴离散变量标签中的空格替换为换行符,以使得标签更加易于阅读。注意不要改变原有的意思。 - Alex Thomas