我有这个数据框:
> str(DF)
'data.frame': 14084 obs. of 6 variables:
.
.
.
$ Variables: chr "Height" "Height" "Height" "Height" ...
$ Values : num 245 129 301 162 123 125 115 47 46 135 ...
$ Year : Factor w/ 2 levels "2015","2016": 1 1 1 1 1 1 1 1 1 1 ...
Run Code Online (Sandbox Code Playgroud)
我使用facet_wrap()自由轴刻度将图分成两个小平面(分为两列)。
ggplot(data = DF, aes(x = Year, y = Values)) +
geom_boxplot() +
facet_wrap("Variables", scales = "free")
Run Code Online (Sandbox Code Playgroud)
我的问题是:
两个构面共享一个共同的y轴标题。但是,我想为两个方面提供两个单独的y轴标题。常见的x轴标题对我来说很好。
我碰到了这个问题, 使用带有facet_wrap的ggplot2显示不同的轴标签, 但是它并不能解决我想要的问题,因为我不想失去顶部的切面标签。而且,我的构面是水平排列的。
我尝试使用labs():
. . . +
labs(y=c("A", "B"))
Run Code Online (Sandbox Code Playgroud)
但这只是将第一个构面的y轴标题更改为A,而第二个构面则保持不变。
我该如何解决这个问题?
任何帮助,将不胜感激。
不知道我是否完全了解您的需求,但这是我根据您建议的链接和此链接进行的尝试。
library(ggplot2)
library(grid)
library(gtable)
# Some fake data
set.seed(2018)
df <- data.frame(variables = rep(c("var1", "var2"), times = 100),
values = rnorm(100),
year = as.factor(2001:2010))
# Make a plot with positioning the strip labels to the right of each facet,
# acting as OY axis titles.
# We will add the top strip labels in the next step,
# using the `grid` & `gtable` packages functionality.
p <- ggplot(df, aes(x = year, y = values, group = year) ) +
geom_boxplot() +
facet_wrap(~ variables, scales = "free_y", nrow = 1,
strip.position = "left",
labeller = as_labeller(c(var1 = "Example var1",
var2 = "Example var2") ) ) +
ylab(NULL) +
theme(strip.background = element_blank(),
strip.placement = "outside",
# Customize theme so that is black & white style as requested
panel.background = element_rect(fill = NA, colour = 'black'),
panel.grid = element_blank())
p
Run Code Online (Sandbox Code Playgroud)
使用grid&gtable软件包的功能添加顶部标签条:
# Get gtable object
g <- ggplotGrob(p)
# Sometimes helpful to get an idea about the grobs' position
grid.show.layout(gtable:::gtable_layout(g))
# Add an extra top row (make some space)
g <- gtable_add_rows(x = g, heights = unit(0.65, 'cm'), pos = 2)
# First strip
g <- gtable_add_grob(x = g,
grobs = list(rectGrob(gp = gpar(col = NA,
fill = NA)),
textGrob(label = "var1",
gp = gpar(col = "black"))),
t = 3, l = 7, b = 3, r = 7,
name = c("strip-top-1-rectg", "strip-top-1-text"))
# Second strip
g <- gtable_add_grob(x = g,
grobs = list(rectGrob(gp = gpar(col = NA,
fill = NA)),
textGrob(label = "var2",
gp = gpar(col = "black"))),
t = 3, l = 13, b = 3, r = 13,
name = c("strip-top-2-rectg", "strip-top-2-text"))
# Draw the edited plot
grid.newpage()
grid.draw(g)
Run Code Online (Sandbox Code Playgroud)