Add a legend when one already exists
1
0
Entering edit mode
16 months ago
Loïs • 0

Hello,

I have the following R code which allows me to make a heatmap, as follows :

library(ggplot2)
library(ggtext)

test_data <- read.csv("/home/veillat/Bureau/heatmap.csv")
test_data$Species <- factor(test_data$Species, levels = unique(test_data$Species))
test_data$Conditions <- factor(test_data$Conditions, levels = unique(test_data$Conditions))

# Définition des couleurs en fonction de la colonne "Conservation"
color_mapping <- c("wet" = "blue", "dry" = "darkgoldenrod1", "Hand collected" = "darkgreen")

# Ajouter une colonne avec les étiquettes colorées pour chaque espèce
test_data$Species_Label <- paste0("<i><span style='color:", color_mapping[test_data$Conservation], "'>", test_data$Species, "</span></i>")

# Réorganiser l'ordre des labels de l'axe X
test_data$Species_Label <- factor(test_data$Species_Label, levels = unique(test_data$Species_Label))

# Création du graphique
ggplot(test_data, aes(x = Species_Label, y = Conditions, fill = Detection)) +
  geom_raster() +
  geom_tile(color = "black", size = 0.3) +
  scale_fill_manual(values = c("green", "red")) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1, face = "italic"),
        strip.text.y = element_blank()) +
  ggtitle("") +
  facet_grid(rows = vars(Conditions), cols = vars(Bulk), scales = "free", space = "free_y") +
  theme(axis.text.x = element_markdown()) +
  guides(x = guide_axis(n.dodge = 1)) +
  xlab("Species")+
  labs(fill = "Detection and Collection type")

enter image description here

I'd have to add information about the colours of the labels on the X axis to the existing legend. So in my case a blue square corresponding to condition 1, a dark yellow square for condition 2 and a dark green square for condition 3.

How can I do this?

Thanks in advance

R legend heatmap • 533 views
ADD COMMENT
0
Entering edit mode
16 months ago
iraun 6.2k

You could use Legend from ComplexHeatmap package.

lgd = Legend(labels = names(color_mapping), title = "Legend title", labels_gp = gpar(fontsize = 10), legend_gp = gpar(fill = color_mapping))
draw(lgd)

I haven't tested the code with your specific example, but I hope it serves you as guide :).

ADD COMMENT

Login before adding your answer.

Traffic: 1984 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6