我使用了以下ggplot命令:
ggplot(survey, aes(x = age)) + stat_bin(aes(n = nrow(h3), y = ..count.. / n), binwidth = 10)
+ scale_y_continuous(formatter = "percent", breaks = c(0, 0.1, 0.2))
+ facet_grid(hospital ~ .)
+ theme(panel.background = theme_blank())
Run Code Online (Sandbox Code Playgroud)
生产

我想将facet标签更改为更短的标签(如Hosp 1,Hosp 2 ......),因为它们现在太长并且看起来很狭窄(增加图形的高度不是一个选项,它需要文档中的空间太大).我查看了facet_grid帮助页面,但无法弄清楚如何.
我想创建自己的贴标函数来获取构面标签的输入,将其转换为包含数学符号的字符串,然后让 ggplot 解析它。我知道我可以更改底层数据并使用label_parsed,但希望能够创建其他人可以使用的易于通用的函数。这还允许人们保持数据原样(包括正确的因子水平)并仅交换标签。否则,您需要改变基础数据,然后添加正确的因子级别,以便正确完成排序。
阅读http://ggplot2.tidyverse.org/reference/labeller.html后,这是我尝试过的。
library(ggplot2)
## can be used with label_parsed but order not retained
mtcars$mpg2 <- ifelse(mtcars$mpg > 20, 'beta', 'alpha')
## can be used with label_parsed and retains levels (but this is 2 steps)
mtcars$mpg3 <- factor(mtcars$mpg2, levels = c('beta', 'alpha'))
ggplot(mtcars, aes(mpg, disp)) +
geom_point() +
facet_grid(mpg3 ~ mpg2,
labeller = label_parsed
)
## attempt #1 at a function
label_as_notation <- function(x, ...){
parse(text = paste('"X:" ~ ', x, '<=', ifelse(x == 0, …Run Code Online (Sandbox Code Playgroud) 我在 R 中使用 ggplot 创建了以下图:
代码:
ggplot(hola, aes(.fitted, .resid, color=type)) +
geom_point() +
geom_hline(yintercept = 0, color="black") +
geom_smooth(se = FALSE, color="darkblue")+facet_wrap( type~exp, scales = "free") +
scale_color_manual(values=c("#5fb772", "#5fabb7"))
Run Code Online (Sandbox Code Playgroud)
然而,我认为facet_wrap标签看起来太大并且破坏了整体图形的外观;有没有办法以更好看的方式显示它?就像将 df 的两列合并为一列?或将面标签合并在一行中?
PD:顺便说一下,使用facet_grid 不是一个选项,因为mu 和abs 的X 轴是不同的。