ggplot2 为分面图中的两个 Y 轴添加单独的图例

2023-11-24

我正在尝试在轴标题旁边添加图例。我跟着这个 stackoverflow 答案得到情节。

如何在两个y轴上添加图例?。我想在左右 Y 轴上都有图例。在下图中,右侧 y 轴缺少图例符号。

还可以为类似于图例中的符号的文本提供独特的颜色。

同时,如何将图例键符号旋转到垂直位置?

到目前为止我的代码:

## install ggplot2 as follows:
# install.packages("devtools")
# devtools::install_github("hadley/ggplot2")

packageVersion('ggplot2')
# [1] ‘2.2.0.9000’

packageVersion('data.table')
# [1] ‘1.9.7’

# libraries
library(ggplot2)
library(data.table)

# data
df1 <- structure(list(plate_num = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L,
                                    1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L), 
                      `Before Treatment` = c(662.253098499674, 684.416067929458, 688.284595300261, 
                                             692.532637075718, 728.988910632746, 684.708496732026, 
                                             703.390706806283, 673.920966688439, 644.945573770492, 504.423076923077, 
                                             580.263743455497, 580.563767168084, 689.6014445174, 804.740789473684, 
                                             815.792020928712, 789.234139960759, 778.087753765553, 745.777922926192, 
                                             787.762434554974, 780.828758169935, 781.265839320705, 732.683552631579, 
                                             773.964052287582, 713.941253263708, 724.459070072037, 838.899148657498),
                      `After Treatment` = c(440.251141552511, 431.039190071848, 460.349216710183, 479.798955613577, 
                                            441.123939986954, 436.17908496732, 453.938481675393, 437.237753102547,
                                            448.52, 426.70925684485, 390.417539267016, 359.66121648136, 451.969796454366, 
                                            515.611842105263, 542.325703073904, 547.637671680837, 518.316306483301, 478.536903984324, 
                                            501.122382198953, 494.475816993464, 474.581319399086, 438.515789473684, 
                                            440.251633986928, 407.945822454308, 413.571054354944, 537.290111329404),
                      Ratio = c(1.50426208132996, 1.58782793698034, 1.49513580194398, 1.443380876455, 1.6525716347526, 
                                1.56978754903694, 1.54952870311901, 1.54131467812749, 1.43794161636157, 1.18212358609901, 1.48626453756382, 
                                                 1.61419619509676, 1.5257688675819, 1.5607492376201, 1.50424738548219, 
                                                 1.44116115594897, 1.50118324280547, 1.55845435684647, 1.57199610821259, 
                                                 1.57910403569899, 1.64622122149676, 1.67082593197148, 1.75800381540563, 
                                                 1.75008840381905, 1.75171608951693, 1.56135229547), 
                      grp = c("wt-3X", "wt-3X", "wt-3X", "wt-3X", "wt-3X", "wt-3X", "wt-3X", "wt-3X", "wt-3X", "wt-3X",
                              "wt-3X", "wt-3X", "wt-3X", "mu-3X", "mu-3X", "mu-3X", "mu-3X", "mu-3X", "mu-3X", "mu-3X", 
                              "mu-3X", "mu-3X", "mu-3X", "mu-3X", "mu-3X", "mu-3X")),
                 .Names = c("plate_num", "Before Treatment", "After Treatment", "Ratio", "grp"),
                 row.names = c(NA, -26L), class = "data.frame")


max1 <- max(c(df1$`Before Treatment`, df1$`After Treatment`))
max2 <- max(df1$Ratio)
df1$norm_ratio <- df1$Ratio / (max2/max1)
df1 <- melt(df1, id = c("plate_num", 'grp'))
df1$plate_num <- factor(df1$plate_num, levels = 1:13, ordered = TRUE)

# plot
p <- ggplot(mapping = aes(x = plate_num, y = value, group = variable)) +
  geom_line(data = subset(df1, variable %in% c('Before Treatment', 'After Treatment')), aes(color = variable), size = 1, show.legend = TRUE) +
  geom_point(data = subset(df1, variable %in% c('Before Treatment', 'After Treatment')), aes(color = variable), size = 2, show.legend = TRUE) +
  scale_color_manual(values = c('green', 'blue'), guide = 'legend') + 
  geom_line(data = subset(df1, variable %in% c('norm_ratio')), aes(color = variable), col = 'red', size = 1) +
  geom_point(data = subset(df1, variable %in% c('norm_ratio')), aes(color = variable), col = 'red', size = 2) +
  facet_wrap(~ grp) +
  scale_y_continuous(sec.axis = sec_axis(trans = ~ . * (max2 / max1),
                                         name = 'Ratio of Main Effect of Before and After Treatment\n')) +

  theme_bw() + 
  theme(axis.text.x = element_text(size=15, face="bold", angle = 0, vjust = 1), 
        axis.title.x = element_text(size=15, face="bold"),
        axis.text.y = element_text(size=15, face="bold", color = 'black'),
        axis.text.y.right = element_text(size=15, face="bold", color = 'red'),
        axis.title.y.right = element_text(size=15, face="bold", color = 'red'),
        axis.title.y = element_text(size=15, face="bold"),
        axis.ticks.length=unit(0.5,"cm"),
        legend.position = c(-0.28, 0.4),
        legend.direction = 'vertical',
        legend.text = element_text(size = 15, angle = 90),
        legend.key = element_rect(color = NA, fill = NA),
        legend.key.width=unit(2,"line"),
        legend.key.height=unit(2,"line"),
        legend.title = element_blank(),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        strip.text.x = element_text(size=15, face="bold", color = "black", angle = 0),
        plot.margin = unit(c(1,4,1,3), "cm")) +
  ylab('Main Effect of TDP43\n\n\n') + 
  xlab('\nPlate Number')

print(p)

enter image description here


为了让它更短一些,我删掉了你的theme定义。


我利用了这样一个事实,即您可以从 ggplot 元素中提取单个 grobs。在本例中,我们提取 3 个图例。

为了获得所需的结果,我们需要创建 4 个图:

  1. Plot p:没有传说的剧情
  2. Plot l1:绿色传奇的剧情
  3. Plot l2:蓝色传说的情节
  4. Plot l3:红色传说的剧情

我们利用该函数get_legend()这是套餐的一部分cowplot。它可以让您提取情节的图例。

在我们提取左侧的两个图例后,我们使用arrangeGrob将它们组合起来并命名组合图例llegend。 当我们提取出红色图例后,我们grid.arrange绘制所有三个对象(llegend, p and rlegend).

关于图例键的方向,您应该注意到我们将图例打印在相应图的顶部。这样我们就可以使用editGrob在提取图例后旋转(组合的)图例,并且图例键具有正确的方向。

这是全部代码:

library(ggplot2)
library(gridExtra)
library(grid)
library(cowplot)

# actual plot without legends
p <- ggplot(mapping = aes(x = plate_num, y = value, group = variable)) +
  geom_line(data = subset(df1, variable %in% c('Before Treatment', 'After Treatment')), aes(color = variable), size = 1, show.legend = F) +
  geom_point(data = subset(df1, variable %in% c('Before Treatment', 'After Treatment')), aes(color = variable), size = 2, show.legend = F) +

  geom_line(data = subset(df1, variable %in% c('norm_ratio')), aes(color = 'Test'), col = 'red', size = 1) +
  geom_point(data = subset(df1, variable %in% c('norm_ratio')), aes(color = 'Test'), col = 'red', size = 2) +
  facet_wrap(~ grp) +
  scale_y_continuous(sec.axis = sec_axis(trans = ~ . * (max2 / max1),
                                         name = 'Ratio of Main Effect of Before and After Treatment\n')) +
  scale_color_manual(values = c('green', 'blue'), guide = 'legend') +
  theme_bw() + 
  theme(axis.text.x = element_text(size=11, face="bold", angle = 0, vjust = 1), 
        axis.title.x = element_text(size=11, face="bold"),
        axis.text.y = element_text(size=11, face="bold", color = 'black'),
        axis.text.y.right = element_text(size=11, face="bold", color = 'red'),
        axis.title.y.right = element_text(size=11, face="bold", color = 'red', margin=margin(0,0,0,0)),
        axis.title.y = element_text(size=11, face="bold", margin=margin(0,-30,0,0)),
        panel.grid.minor = element_blank(),
        strip.text.x = element_text(size=15, face="bold", color = "black", angle = 0),
        plot.margin = unit(c(1,1,1,1), "cm")) +
  ylab('Main Effect of TDP43\n\n\n') + 
  xlab('\nPlate Number')

# Create legend on the left 
l1 <- ggplot(mapping = aes(x = plate_num, y = value, group = variable)) +
  geom_line(data = subset(df1, variable %in% c('Before Treatment')), aes(color = variable), size = 1, show.legend = TRUE) +
  geom_point(data = subset(df1, variable %in% c('Before Treatment')), aes(color = variable), size = 2, show.legend = TRUE) +
  scale_color_manual(values = 'green', guide = 'legend') +
  theme(legend.direction = 'horizontal', 
        legend.text = element_text(angle = 0, colour = c('green', 'blue')),
        legend.position = 'top',
        legend.title = element_blank(),
        legend.margin = margin(0, 0, 0, 0, 'cm'),
        legend.box.margin = unit(c(0, 0 , -2.5 ,0), 'cm'))

l2 <- ggplot(mapping = aes(x = plate_num, y = value, group = variable)) +
  geom_line(data = subset(df1, variable %in% c('After Treatment')), aes(color = variable), size = 1, show.legend = TRUE) +
  geom_point(data = subset(df1, variable %in% c('After Treatment')), aes(color = variable), size = 2, show.legend = TRUE) +
  scale_color_manual(values = 'blue', guide = 'legend') +
  theme(legend.direction = 'horizontal', 
        legend.text = element_text(angle = 0, colour = c('blue')),
        legend.position = 'top',
        legend.title = element_blank(),
        legend.margin = margin(0, 0, 0, 0, 'cm'),
        legend.box.margin = unit(c(0, 0 , -2.5 ,0), 'cm'))

legend1 <- get_legend(l1)
legend2 <- get_legend(l2)

# Combine green and blue legend
llegend <- editGrob(arrangeGrob(grobs = list(legend1, legend2), 
                       nrow = 1, ncol = 2), vp = viewport(angle = 90))

# Plot with legend on the right
l3 <- ggplot(mapping = aes(x = plate_num, y = value, group = variable)) +
   geom_line(data = subset(df1, variable %in% c('norm_ratio')), aes(color = variable), size = 1) +
  geom_point(data = subset(df1, variable %in% c('norm_ratio')), aes(color = variable), size = 2) +
  scale_color_manual(values = 'red', guide = 'legend') +
  theme(legend.direction = 'horizontal', 
        legend.text = element_text(angle = 0, colour = 'red'),
        legend.position = 'top',
        legend.title = element_blank(),
        legend.margin = margin(0, 0, 0, 0, 'cm'),
        legend.box.margin = unit(c(0, 0, -3, 0), 'cm'))

# extract legend
rlegend <- editGrob(get_legend(l3), vp = viewport(angle = 270))

grid.arrange(grobs = list(llegend, p, rlegend), ncol = 3, 
             widths = unit(c(3, 16, 3), "cm"))

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ggplot2 为分面图中的两个 Y 轴添加单独的图例 的相关文章

  • 关于子组的新列和另一列中的百分比范围

    我有一个如下所示的示例 df df test lt data frame Group Name c Group1 Group2 Group1 Group2 Group2 Group2 Group1 Sub group name c A A
  • 距数据帧中最近的非 NA 值的距离

    我有以下数据帧 df 我想添加一列 其中包含与每行最接近的非 NA 值的距离 df lt data frame x 1 20 df c 1 3 4 5 11 14 15 16 x lt NA 换句话说 我正在寻找以下值 df distanc
  • 如何更改 r 中的树状图标签

    我在 R 中有一个树形图 它基于使用 hclust 的分层聚类 我正在对不同颜色的标签进行着色 但是当我尝试使用以下命令更改树图的标签 集群所基于的数据帧的行 时dendrogram dendrogram gt set labels dat
  • 配置 fix() 和 edit() 以从 R/RStudio 在 Notepad++ 中打开

    当我在 RStudio 或 RGUI 中执行此操作时 fix SomeFunction 或使用edit 我可以在记事本中看到该函数的代码 有什么方法可以更改此设置 以便代码预览在 Notepad 中打开 而不是在普通的旧记事本中打开 同样
  • R中使用余弦距离的层次聚类

    我想通过使用余弦相似度与 R 编程语言对文档语料库进行层次聚类 但出现以下错误 if is na n n gt 65536L stop 大小不能为 NA 或 超过 65536 需要 TRUE FALSE 时缺少值 我应该怎么办 为了重现它
  • R正则表达式获取第二个下划线之前的所有文本

    s lt 1 343 43Hello 2 323 14 fdh 99H 在 R 中 我想使用正则表达式来获取第二个下划线之前的子字符串 如何使用一个正则表达式来完成此操作 另一种方法是用 分割 然后粘贴前两个 一些东西 paste sapp
  • Shiny:从DT数据表中选定的行获取信息

    我们正在尝试重新创建示例 https demo shinyapps io 029 row selection https demo shinyapps io 029 row selection 使用DT包来渲染数据帧而不是shiny包 DT
  • R,igraph,是否可以用图案填充顶点

    使用 R 和 igraph 绘制图形 我使用颜色来标记顶点类型 请参阅下面的代码 是否可以用图案而不是颜色填充顶点 以便在以彩色和黑白查看时可以区分节点类型 我需要 4 种独特的颜色 图案 colorbrewer 中唯一适合的调色板是这个
  • 使用 R SOAP (SSOAP) 检索数据/抓取

    在 B cycle 页面 www bcycle com whowantsitmore aspx 上 我试图抓取投票的位置和值 The URL http mapservices bcycle com bcycleservice asmx ht
  • Shiny :针对所有错误显示一条消息

    我在 R 的 Shiny 中有一个应用程序 我想处理消息 以便用户看不到发生了什么错误 我知道通过 tags style type text css shiny output error visibility hidden shiny ou
  • R 中具有 p 值的相关矩阵

    假设我想要传导相关矩阵 library dplyr data iris iris gt select if is numeric gt cor y iris Petal Width method spearman gt round 2 现在
  • 如何创建 highcharter 事件函数以在 Shiny R 中创建“下拉函数”

    我正在建造一个shiny应用程序 我想要完成的事情之一是创建一个下拉菜单 我想将劳动力变量绘制为不同级别的年份变量的函数 请参阅下面的示例数据框 year level 2 level 3 labour 1 2013 10 101 1 2 2
  • R 无法回忆起内存中的对象

    我正在构建一个包含多个步骤的函数 其中每个步骤都会创建一个对象 某个步骤失败 temp3 并且无法找到前面的步骤对象 错误 未找到对象 temp2 我不知道为什么 我有类似的函数 遵循完全相同的结构 每个步骤都遵循先前创建的对象 在函数内
  • 连接树状图和热图

    我有一个heatmap 一组样本的基因表达 set seed 10 mat lt matrix rnorm 24 10 mean 1 sd 2 nrow 24 ncol 10 dimnames list paste g 1 24 sep p
  • R中具有特定条件的多列变异

    我有这个数据 M1 M2 M3 UCL 1 2 3 1 5 我想在这种情况下创建新列 如果M1大于UCL MM1将为 UP 否则为 NULL 如果M2大于UCL MM2将为 UP 否则为 NULL 如果M3大于UCL MM3将为 UP 否则
  • 如何对范围内的行进行分组并考虑第三列?

    我有一个遗传数据集 我想对基因组中物理上靠近的遗传变异 行进行分组 我想对每条染色体基因组中某些点范围内的基因进行分组 chrom 我的 点 数据集包含变体 行需要在一定范围内的位置 如下所示 chrom low high 1 500 17
  • 使用 data.table 左连接

    假设我有两个数据表 s dataA A B 1 1 12 2 2 13 3 3 14 4 4 15 dataB A B 1 2 13 2 3 14 我有以下代码 merge test merge dataA dataB by A all d
  • 如何使用 Facet R 添加线条[重复]

    这个问题在这里已经有答案了 所以我有一个多面图 我希望能够向其中添加随每个面而变化的线 这是代码 p lt ggplot mtcars aes x wt geom histogram bins 20 aes fill factor cyl
  • 如何将 Shiny 中生成的反应图传递到 Rmarkdown 以生成动态报告

    简而言之 我希望能够通过单击按钮从我的闪亮应用程序生成动态 Rmarkdown 报告文件 pdf 或 html 为此 我想我将使用 Shiny 的参数化报告 但不知何故 我无法将单个谜题转移到所需的目标 使用此代码 我们可以在 R Shin
  • 按名称包含在单个对象中的多个列对 data.frame 进行排序?

    我想排序一个data frame由多列组成 理想情况下使用基础 R 无需任何外部包 尽管如果有必要 就这样吧 读过如何按列对数据框进行排序 https stackoverflow com questions 1296646 how to s

随机推荐

  • 在哪里可以找到 System.Web.Helpers、System.Web.WebPages 和 System.Web.Razor?

    我正在关注这个article在 RazorGenerator 上 它说我必须添加对以下内容的引用 System Web Helpers dll System Web WebPages dll System Web Razor dll 当我这
  • 如何在颤动中绘制带有尖头的线/渐变线/?

    使用描边方法 如何在颤动中创建带有尖头的渐变线 我想在颤振中画出如下线 使用CustomPainter进行绘制 import package flutter material dart void main gt runApp Example
  • 解码base64字符串 - php

    有什么办法可以解码这个字符串吗 实际字符串 其他语言测试 testing 发送邮件时进行 base64 编码 主题为 iso 2022 jp B GyRCQjZCPjhsOEBCLDtuGyhCIC0gdGVzdGluZw 这是base 6
  • Emacs 字体锁定模式:提供自定义颜色而不是面孔

    On 本页讨论字体锁定模式 提供了一个突出显示自定义模式的示例 add hook c mode hook lambda font lock add keywords nil lt FIXME 1 font lock warning face
  • 获取 std::any 的大小

    有什么方法可以获取存储的数据的大小 以字节为单位 std any 我想出的唯一解决方法是通过以下方式查询其值的类型std any type并将结果与 已知类型的列表进行比较 例如my any type typeid T 那么尺寸就是size
  • HTML 中的
  • 标签有结束标签吗?
  • 所以 我在大学学习 HTML 中的列表 教授说 li 没有结束标签 li 以及其他一些标签 例如 img and br 这是否正确 因为我见过很多模板 主题使用 The li element有一个结束标记 but 这是可选的在某些情况下 A
  • 如何获取节点子模块的模块

    假设模块 X 有一个 Y 子模块 从依赖于 X 的节点应用程序中 我如何需要子模块 Y var Y require X Y 结果是Cannot find module X Y 子模块意味着从 X 模块内部导出 Try require X p
  • C# 双精度数相除时精度损失

    我知道这已经被讨论了一次又一次 但我似乎无法得到哪怕是最简单的双精度单步除法的例子 以在 C 中产生预期的 不四舍五入的结果 所以我想知道是否可能即有一些编译器标志或其他我没有想到的奇怪的东西 考虑这个例子 double v1 0 7 do
  • MVVM Light:在 XAML 中添加 EventToCommand 而无需 Blend,更简单的方法或片段?

    谁能告诉我实际的语法是什么EventToCommand班级 据我所知EventToCommand类适用于 Silverlight WPF 和 WP7 因此我认为这是一个更好的选择 据我所知 我可以添加任何点击事件并将其强制到我的ViewMo
  • wait()/notify()同步

    我正在尝试检查等待 通知在java中如何工作 Code public class Tester public static void main String args MyRunnable r new MyRunnable Thread t
  • UIPageViewController 方向仅向前

    目标是创建一个只能向前导航的 UIPageViewController 我正在使用数据源为 UIPageViewController 提供内容 方向设置为UIPageViewControllerNavigationDirectionForw
  • 使用 Jython 将我的 Python 脚本作为 JAR 文件分发?

    我成为一名 Python 程序员已经快两年了 我习惯于编写小脚本来自动执行一些我必须在办公室执行的重复性任务 现在 显然我的同事注意到了这一点 他们也想要这些脚本 他们中有些人有 Mac 有些人有 Windows 我在窗户上做了这些 我研究
  • 以编程方式获取谷歌搜索结果计数的最简单(合法)方法?

    我想使用 Java 代码获取某些 Google 搜索引擎查询 在整个网络上 的估计结果数 我每天只需要执行很少的查询 所以一开始Google 网页搜索 API 虽然已弃用 但似乎足够好 参见例如如何以编程方式搜索 Google Java A
  • 如何同时使用“gulp-babel”和“gulp-browserify”

    我尝试编写这些代码 gulp task script function use strict return gulp src app js components jsx pipe babel pipe browserify pipe gul
  • Windows 上有获取路线信息的 C/C++ API 吗?

    是否有 Windows 或 cygwin C C API 来收集 Windows 上的路由命令提供的信息 我对路线指标特别感兴趣 这是路由输出的示例 IP 已更改以保护无辜者 route PRINT 4 Interface List 11
  • 在android中从Google Plus获取用户名

    我已将 Google plus 与我的 Android 应用程序集成 一切工作正常 我也连接到 Google plus 但我无法获取当前登录用户的名称 public void onConnected Bundle connectionHin
  • Wix - 如何在没有 UI 的情况下运行/安装应用程序

    我有 exe 文件 需要将其转换为 msi 并使用组策略在域中的更多计算机上安装它 而无需用户交互 我找到了这个教程https stackoverflow com questions 19271862 wix how to run exe
  • 从 Word 中复制 Mathml 格式的方程

    我使用内置的方程编辑器在 Word 2013 中创建了大量数学方程 我需要将这些方程输入到支持 mathml 的基于浏览器的编辑器 带有 fmath 插件的 CKEditor 中 有没有办法从word复制这些方程并将它们作为mathml粘贴
  • 设置 WPF TabControl 为每个选项卡显示相同的内容

    我想使用 TabControl 其中每个选项卡显示相同的视图 只是参数不同 因此 我不想为每个选项卡创建新的内容控件 而是为所有选项卡重用相同的控件 将其某些属性绑定到SelectedItem的财产TabControl 我尝试将我包含的控件
  • ggplot2 为分面图中的两个 Y 轴添加单独的图例

    我正在尝试在轴标题旁边添加图例 我跟着这个 stackoverflow 答案得到情节 如何在两个y轴上添加图例 我想在左右 Y 轴上都有图例 在下图中 右侧 y 轴缺少图例符号 还可以为类似于图例中的符号的文本提供独特的颜色 同时 如何将图