ggtree icon indicating copy to clipboard operation
ggtree copied to clipboard

gheatmap() fails on ggplot2 4.0 because attr(p, "mapping") becomes a global aesthetic

Open xiehs211 opened this issue 1 year ago • 3 comments

Summary

gheatmap() attaches the heatmap column metadata via attr(p, "mapping") <- mapping. ggplot2 4.0 treats this as a global aesthetic, so stat_tree() receives the 3-row heatmap mapping and errors with “Fix the following mappings: from, to, .panel”.

Environment

  • R 4.5.1
  • ggtree 3.16.3
  • ggplot2 4.0.1
  • ape 5.8-1

Minimal Reproduction

library(ggtree) library(ape)

tree <- rtree(5) mat <- matrix(runif(10), nrow = 5, dimnames = list(tree$tip.label, c("A", "B")))

p <- ggtree(tree) gheatmap(p, mat)

Error in `stat_tree()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the
  data (9).
✖ Fix the following mappings: `from`, `to`, and `.panel`.
Run `rlang::last_trace()` to see where the error occurred.

Analysis / Workaround

Removing/renaming that attribute restores plotting: p2 <- gheatmap(p, mat) attr(p2, "mapping") <- NULL print(p2)

Image

Suggested Fix

Rename the attribute (e.g. attr(p, "heatmap_mapping")) or drop it so ggplot2 no longer confuses it with the global mapping slot.

xiehs211 avatar Nov 29 '25 15:11 xiehs211

Thank you for posting the workaround - I had the same error when trying to plot a heatmap with the current version of ggtree. In using your workaround I had a secondary error, which looked like this:

attr(p_final, "mapping") <- NULL print(p_final) Error in geom_segment2(): ! Problem while converting geom to grob. Error occurred in the 3rd layer. Caused by error in is.waive(): ! could not find function "is.waive" Run rlang::last_trace() to see where the error occurred.

Adding the following line has allowed me to (at least temporarily) solve this problem and print my heatmap:
is.waive <- function(x) inherits(x, "waiver")

lou-campbell33 avatar Dec 01 '25 04:12 lou-campbell33

Re-install ggtree with:

install.packages("devtools") devtools::install_github("YuLab-SMU/ggtree")

alrasheda avatar Jan 15 '26 11:01 alrasheda

Thanks for the analysis — it was exactly right. gheatmap() attached the heatmap column metadata via attr(p, "mapping") <- mapping, which ggplot2 4.0 picks up as a global aesthetic, so stat_tree() received the heatmap mapping and complained about from, to and .panel.

Renaming/dropping that attribute is what b6dffa9 did, so the suggested fix is already in. Verified against ggplot2 4.0.3 with your minimal reproduction (rtree(5) + a 5x2 matrix): it builds and draws, and the tree layer still sees its 9 nodes. The workaround attr(p2, "mapping") <- NULL is no longer needed.

Regression test added in tests/testthat/test-gheatmap.R, which asserts the attribute is never a data.frame.

GuangchuangYu avatar Sep 14 '26 01:09 GuangchuangYu