r - 如何使用 ggplot 在 R 中创建不均匀的 facet_wrap 网格?
问题描述
我目前正在使用 R 中的 ggplot2 绘制一个图表,我想在其中使用 facet_wrap 创建 5 个子图。
到目前为止,这是我的代码:
# getting the data
data = structure(list(type = c("red", "blue", "orange", "yellow", "green",
"red", "blue", "orange", "yellow", "green", "red", "blue", "orange",
"yellow", "green", "red", "blue", "orange", "yellow", "green"),
cond = c("new", "new", "new", "new", "new", "old", "old",
"old", "old", "old", "new", "new", "new", "new", "new", "old",
"old", "old", "old", "old"), fact = c("light", "light", "light",
"light", "light", "light", "light", "light", "light", "light",
"shiny", "shiny", "shiny", "shiny", "shiny", "shiny", "shiny",
"shiny", "shiny", "shiny"), score = c(2L, 4L, 8L, 6L, 10L, 3L,
5L, 9L, 1L, 3L, 12L, 14L, 18L, 16L, 20L, 13L, 15L, 19L, 11L,
13L)), class = "data.frame", row.names = c(NA, -20L))
library(ggplot2)
ggplot(data=data, aes(x=cond, y=score, fill=fact)) +
geom_bar(stat="identity", position=position_dodge()) +
theme_bw() + facet_wrap(. ~ type, ncol=3)
这将创建以下图:
但是,由于其中一种颜色比其他颜色重要得多,我想创建以下选项之一:
有谁知道如何让 facet_wrap 做到这一点,或者可以指出另一个选项来创建它?
干杯,马克斯
解决方案
这是混合patchwork
和方面的方法。
blue
为其他所有内容创建一个情节。从蓝色图中删除图例,并从另一个图中删除 y 轴标题。
library(tidyverse)
library(patchwork)
p_other <-
data %>%
filter(type != "blue") %>%
ggplot(aes(x = cond, y = score, fill = fact)) +
geom_bar(stat = "identity", position = position_dodge()) +
theme_bw() +
facet_wrap(. ~ type, ncol = 2) +
theme(axis.title.y = element_blank())
p_blue <-
data %>%
filter(type == "blue") %>%
ggplot(aes(x = cond, y = score, fill = fact)) +
geom_bar(stat = "identity", position = position_dodge()) +
theme_bw() +
facet_wrap(. ~ type, ncol = 2) +
theme(legend.position = "none")
|
使用from patchwork添加一列。
(p_blue | p_other) + plot_layout(widths = c(1, 2))
推荐阅读
- python-3.x - 当嵌套在具有多个参数的条件中时,pdb 不会在 continue 语句上停止
- node.js - 回调不是函数:(
- excel - 文档锁定编辑
- c++ - 为什么ifstream读取超出eof?(即使没有打开文件)如何在 eof 处停止读取?
- r - 如何根据组向嵌套图添加额外的标题组件
- python - 根据列名计算并获取名称作为计算的一部分
- c# - 为什么我只能在我的 android 通知中按一次播放/暂停按钮?
- angular - Angular Dialog “Popup” 编辑数据
- r - 为什么 position_dodgev 不总是在 ggplot 中的错误栏上工作?
- html - 使用工具提示创建悬停消息不会为多个悬停消息产生相同的结果