gpt4 book ai didi

r - 在ggplot2中通过labeller=label_wrap包裹长轴标签

转载 作者:行者123 更新时间:2023-12-03 07:06:10 28 4
gpt4 key购买 nike

我想自动将标签包装在 ggplot2 中,即插入长标签的换行符。 Here写了如何为其编写函数 (1),但遗憾的是我不知道将 labeller=label_wrap 放在我的代码 (2) 中。

(1) 哈德利函数

label_wrap <- function(variable, value) {
lapply(strwrap(as.character(value), width=25, simplify=FALSE),
paste, collapse="\n")
}

(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")

Histogram with long label not wrapped

我想在这里包装一些较长的标签。

最佳答案

您不需要 label_wrap 函数。请改用 stringr 包中的 str_wrap 函数。

您没有提供 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

现在将标签应用到 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))

enter image description here

关于r - 在ggplot2中通过labeller=label_wrap包裹长轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21878974/

28 4 0