我正在尝试使用左右两个面板制作多面图。 x轴上的变量是连续的,y轴上的变量是离散的,带有相对较长的标签。我想将右侧图的y轴放在右侧(并保持左侧的y轴在左侧),以使两个面板不会被的y轴标签分开右侧图。
我已经尝试了几种不同的解决方法(例如cowplot
),但是我无法满足我的要求,因为在我的情节中我还需要一个图例。
这里是一个代表:
library(tidyverse)
region <- sample(words, 20)
panel <- rep(c(0, 1), each = 10)
value <- rnorm(20, 0, 1)
df <- tibble(region, panel, value)
ggplot(df, aes(value, region)) +
geom_point() +
facet_wrap(~ panel, scales = 'free_y')
谢谢!
此解决方案在具有多于2个图的情况下缺乏灵活性,但它可以为您的情况提供帮助。想法是分别生成图并将这些图合并到一个列表中。 ggplot
函数调用包含if else
层的scale_y_discrete
函数,该函数根据panel
的值将y轴放在左侧还是右侧。我们使用gridExtra
合并图。
library(tidyverse)
library(gridExtra)
region <- sample(words, 20)
panel <- rep(c(0, 1), each = 10)
value <- rnorm(20, 0, 1)
df <- tibble(region, panel, value)
panel <- sort(unique(df$panel))
plot_list <- lapply(panel, function(x) {
ggplot(data = df %>% filter(panel == x),
aes(value, region)) +
geom_point() +
if (x == 0) scale_y_discrete(position = "left") else scale_y_discrete(position = "right")
})
do.call("grid.arrange", c(plot_list, ncol = 2))
您可以离开facet_wrap(~ panel, scales = 'free_y')
图层,并将条形图保留在图形的顶部。
UPDATE
代码已更新,可以从各个图中删除x轴,并在网格图的底部添加文本;添加了第二个if else
来抑制右侧图中的y轴标题。请注意,if else
函数需要用大括号括起来(不知道是不是:-,但这很有意义):
plot_list <- lapply(panel, function(x) {
ggplot(data = df %>% filter(panel == x), aes(x = value, y = region)) +
geom_point() +
theme(axis.title.x = element_blank()) +
facet_wrap(. ~ panel) +
{if (x == 0) scale_y_discrete(position = "left") else scale_y_discrete(position = "right")} +
{if (x == 1) theme(axis.title.y = element_blank())}
})
do.call("grid.arrange", c(plot_list, ncol = 2, bottom = "value"))