通过ggplot2中的labeller = label_wrap包裹长轴标签 [英] Wrap long axis labels via labeller=label_wrap in ggplot2
问题描述
我想将标签自动包裹在ggplot2中,即插入长标签的换行符.
我想在这里包装一些较长的标签.
您不需要 label_wrap
函数.而是使用 stringr
包中的 str_wrap
函数.
您没有提供 df
数据框,因此我创建了一个简单的数据框,其中包含您的标签.然后,将 str_wrap
函数应用于标签.
库(ggplot2)库(字符串)df = data.frame(x = c("label","long label","very,very long label"),y = c(10,15,20))dfdf $ newx = str_wrap(df $ x,width = 10)df
现在将标签应用于ggplot图表:第一个图表使用原始标签;第二个图表使用原始标签.第二张图表使用修改后的标签;对于第三张图表,标签在ggplot调用中进行了修改.
ggplot(df,aes(x,y))+xlab(")+ ylab(参加人数")+geom_bar(stat ="identity")ggplot(df,aes(newx,y))+xlab(")+ ylab(参加人数")+geom_bar(stat ="identity")ggplot(df,aes(x,y))+xlab(")+ ylab(参加人数")+geom_bar(stat ="identity")+scale_x_discrete(labels = function(x)str_wrap(x,width = 10))
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) function by hadley
label_wrap <- function(variable, value) {
lapply(strwrap(as.character(value), width=25, simplify=FALSE),
paste, collapse="\n")
}
(2) code example
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.
You don't need the label_wrap
function. Instead use the str_wrap
function from the stringr
package.
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
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屋!