我想自动将我的标签包装在ggplot2中.这里写了如何为它编写函数(1),但遗憾的是我不知道labeller=label_wrap在我的代码中放入哪里(2).
(1)由hadley执行的功能
label_wrap <- function(variable, value) {
lapply(strwrap(as.character(value), width=25, simplify=FALSE),
paste, collapse="\n")
}
Run Code Online (Sandbox Code Playgroud)
(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")
Run Code Online (Sandbox Code Playgroud)
我想在这里包装一些较长的标签.
San*_*att 123
你不需要这个label_wrap功能.而是使用包中的str_wrap函数stringr.
您没有提供df数据框,因此我创建了一个包含标签的简单数据框.然后,将该str_wrap函数应用于标签.
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
Run Code Online (Sandbox Code Playgroud)
现在将标签应用于ggplot图表:第一个图表使用原始标签; 第二个图表使用修改后的标签; 对于第三个图表,标签在调用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))
Run Code Online (Sandbox Code Playgroud)

Nic*_*uez 17
"鳞片"套餐包括一个非常像克劳德和莱昂纳多的函数:wrap_format.
library(scales)
ggplot(df, aes(x, y)) + geom_bar(stat = "identity") +
labs(x = "", y = "Number of Participants") +
scale_x_discrete(labels = wrap_format(10))
Run Code Online (Sandbox Code Playgroud)
Cla*_*ude 13
这是另一种不参考库的方法stringr:
ggplot(df, aes(x, y)) +
xlab("") + ylab("Number of Participants") +
geom_bar(stat = "identity") +
scale_x_discrete(labels = function(x) lapply(strwrap(x, width = 10, simplify = FALSE), paste, collapse="\n"))
Run Code Online (Sandbox Code Playgroud)
电话:
lapply(strwrap(x, width = 10, simplify = FALSE), paste, collapse="\n")
Run Code Online (Sandbox Code Playgroud)
做动态分割标签的工作.结果与第一个答案中的结果相同.