通过 ggplot2 中的 labeller=label_wrap 包裹长轴标签 [英] Wrap long axis labels via labeller=label_wrap in ggplot2
问题描述
我想在 ggplot2 中自动包装我的标签,即插入长标签的换行符.这里 写了如何为它编写函数 (1),但遗憾的是我没有知道将 labeller=label_wrap
放在我的代码 (2) 中的何处.
I would like to automatically wrap my labels in ggplot2, i.e. insert line breaks of long labels. Here is written how to write a function (1) for it, but sadly I do not know where to put labeller=label_wrap
in my code (2).
(1) 函数由 hadley
(1) function by hadley
label_wrap <- function(variable, value) {
lapply(strwrap(as.character(value), width=25, simplify=FALSE),
paste, collapse="
")
}
(2) 代码示例
df = data.frame(x = c("label", "long label", "very, very long label"),
y = c(10, 15, 20))
ggplot(df, aes(x, y)) + geom_bar(stat="identity")
我想在这里包装一些较长的标签.
I'd like to wrap some of the longer labels here.
推荐答案
您不需要 label_wrap
函数.而是使用 stringr
包中的 str_wrap
函数.
You don't need the label_wrap
function. Instead use the str_wrap
function from the stringr
package.
您没有提供 df
数据框,因此我创建了一个简单的数据框,其中包含您的标签.然后,将 str_wrap
函数应用于标签.
You do not provide your df
data frame, so I create a simple data frame, one that contains your labels. Then, apply the str_wrap
function to the labels.
library(ggplot2)
library(stringr)
df = data.frame(x = c("label", "long label", "very, very long label"),
y = c(10, 15, 20))
df
df$newx = str_wrap(df$x, width = 10)
df
现在将标签应用于 ggplot 图表:第一个图表使用原始标签;第二个图表使用修改后的标签;对于第三个图表,在调用 ggplot 时修改了标签.
Now to apply the labels to a ggplot chart: The first chart uses the original labels; the second chart uses the modified labels; and for the third chart, the labels are modified in the call to ggplot.
ggplot(df, aes(x, y)) +
xlab("") + ylab("Number of Participants") +
geom_bar(stat = "identity")
ggplot(df, aes(newx, y)) +
xlab("") + ylab("Number of Participants") +
geom_bar(stat = "identity")
ggplot(df, aes(x, y)) +
xlab("") + ylab("Number of Participants") +
geom_bar(stat = "identity") +
scale_x_discrete(labels = function(x) str_wrap(x, width = 10))
这篇关于通过 ggplot2 中的 labeller=label_wrap 包裹长轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!