You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何水平翻转ggplot2点阵图并调整标签左右位置?

实现ggplot2点阵图的水平镜像翻转

要实现你需要的沿y轴180度镜像效果,需要对数据和绘图代码做以下几处修改:

修改步骤

  1. 反转x轴变量顺序:让原左侧的变量移到右侧,实现内容左右互换
  2. 调整分面标签位置:将分面标签从左侧移到右侧
  3. 调整y轴刻度位置:让细胞系ID标签显示在左侧

修改后的完整代码

library(dplyr)
library(tidyverse)
library(ggplot2)

df1 <- structure(list(ID = c("OVCAR3", "OVCR", "AFC", "OVCAR3", "OVCR", "AFC", 
                             "OVCAR3", "OVCR", "AFC"), 
                     V = c(1.467, 1.402, 1.445, 1.48, 1.313, 1.418, 1.5, 1.456, 1.489), 
                     N = c(0.823, 0.762, 0.34, 0.738, 0.739, 0.533, 0.891, 0.904, 0.412), 
                     A = c(0.734, 0.771, 1.098, 0.793, 0.799, 0.938, 1.12, 0.853, 1.076), 
                     `N+A` = c(-1.075, -0.577, -0.832, -1.025, -0.633, -0.977, -1.21, -0.517, -1.032), 
                     C = c(-0.239, 0.342, 0.33, -0.314, 0.341, 0.202, -0.324, 0.303, 0.207), 
                     `N+C` = c(-1.403, -1.002, -1.162, -1.5, -1.106, -1.22, -1.329, -1.043, -1.164), 
                     T = c(0.113, 0.487, 0.393, -0.105, 0.336, 0.366, 0.089, 0.329, 0.275), 
                     `N+T` = c(-1.25, -1.045, -1.066, -1.206, -0.981, -0.928, -1.321, -1.12, -1.032), 
                     Group = c("Foci formation", "Foci formation", "Foci formation", 
                               "Soft agar", "Soft agar", "Soft agar", 
                               "3D Matrigel growth", "3D Matrigel growth", "3D Matrigel growth")),
                class = "data.frame", row.names = c(NA, -9L))

# 转换为长格式并反转变量顺序
df_long <- df1 %>% 
  pivot_longer(cols = V:`N+T`, names_to = "Variable", values_to = "Z_score") %>%
  # 反转Variable的因子水平,实现x轴左右翻转
  mutate(Variable = factor(Variable, levels = rev(unique(Variable))))

# 绘制镜像后的点阵图
ggplot(df_long, aes(x = Variable, y = ID, color = Z_score, size = abs(Z_score))) +
  geom_point() +
  # 将分面标签移到右侧
  facet_grid(rows = vars(Group), scales = "free_y", space = "free_y", strip.position = "right") +
  scale_color_gradient2(low = "blue", mid = "white", high = "red", midpoint = 0) +
  theme_minimal() +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1),
    # 确保y轴细胞系ID标签显示在左侧并对齐
    axis.text.y = element_text(hjust = 1),
    # 右侧分面标签保持水平显示
    strip.text.y = element_text(angle = 0)
  ) +
  labs(x = "变量", y = "细胞系ID", color = "Z值", size = "绝对值")

关键修改说明

  • 反转变量顺序:通过mutate(Variable = factor(Variable, levels = rev(unique(Variable))))将x轴变量的顺序完全颠倒,实现左右内容互换
  • 分面标签位置:在facet_grid中添加strip.position = "right",把原左侧的Group分面标签移到右侧
  • y轴刻度调整:axis.text.y = element_text(hjust = 1)确保细胞系ID标签在左侧正确对齐,替换原右侧显示的效果

内容的提问来源于stack exchange,提问作者nicholaspooran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 11:15:14