此问题与如何将长标签包裹在成簇的柱形图/条形图中以使标签出现在多个面板的多行(或多行)中有关。考虑以下数据
df <- data.frame(group=c("Treated very satisfied", "Treated very satisfied",
"Treated not satisfied","Treated not satisfied",
"Untreated very satisfied","Untreated very satisfied",
"Untreated not satisfied","Untreated not satisfied"),
cost=c("low","high","low","high","low","high","low","high"),
treatment=c("treated","treated","treated","treated",
"untreated","untreated","untreated","untreated") ,
value=c(2.3,5.7,4.0,3.1,9.4,3.1,2.0,-1.6))
我们将group作为x轴,将value作为y轴。根据此数据集,使用以下代码生成后续图表
#REORDER
df$group <- factor(df$group, levels = c("Treated very satisfied",
"Treated not satisfied",
"Untreated very satisfied",
"Untreated not satisfied"))
ggplot(data=df,aes(y = value, x = group, fill = cost)) +
geom_bar(stat="identity",position='stack') + ylab("Y label") +
theme(legend.direction = "horizontal",legend.position = "bottom",
legend.spacing.x = unit(0.1, 'cm'))+
theme(legend.title=element_blank())+
geom_text(aes(label = ifelse(value !=0, value, "")),
position = position_stack(vjust=0.5))+
facet_grid( ~ treatment)
[在x轴上,我希望在面板1中看到“非常满意的对待”和“不满意的对待”,第2面板中的“未处理的非常满意”和“未处理的不满意”。如图所示,这些文本重叠,因此无法清晰看到。我正在寻找一种格式化/包装文本(不旋转)的方法,每个文本都沿x轴分成多行(即每行三行),例如,两个面板中的所有标签都对\ n非常满意。
我已经考虑过几次尝试解决此问题的示例,例如,使用包“ stringr”中的函数“ str_wrap”(来自Auto wrapping of labels via labeller=label_wrap in ggplot2)。但是,由于图中的面板/群集,此操作不起作用。我将不胜感激。
首先,我建议使用scales = "free_x"
中的facet_grid
仅显示每个面板中使用的类别。第二。在链接的帖子中使用解决方案对我来说可以很好地包裹标签。
library(ggplot2)
library(stringr)
df <- data.frame(group=c("Treated very satisfied", "Treated very satisfied",
"Treated not satisfied","Treated not satisfied",
"Untreated very satisfied","Untreated very satisfied",
"Untreated not satisfied","Untreated not satisfied"),
cost=c("low","high","low","high","low","high","low","high"),
treatment=c("treated","treated","treated","treated",
"untreated","untreated","untreated","untreated") ,
value=c(2.3,5.7,4.0,3.1,9.4,3.1,2.0,-1.6))
#REORDER
df$group <- factor(df$group, levels = c("Treated very satisfied",
"Treated not satisfied",
"Untreated very satisfied",
"Untreated not satisfied"))
ggplot(data=df,aes(y = value, x = group, fill = cost)) +
geom_bar(stat="identity",position='stack') + ylab("Y label") +
theme(legend.direction = "horizontal",legend.position = "bottom",
legend.spacing.x = unit(0.1, 'cm'))+
theme(legend.title=element_blank())+
geom_text(aes(label = ifelse(value !=0, value, "")),
position = position_stack(vjust=0.5))+
scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) +
facet_grid( ~ treatment, scales = "free_x")
由reprex package(v0.3.0)在2020-06-08创建