Home > Mobile >  Add an additional legend according to the colors of x axis labels
Add an additional legend according to the colors of x axis labels

Time:05-13

I have modified the colors of my x axis labels according to their group. For that, I have used the following pseudocode:

library(ggsci)
library(ggplot2)
x_cols = pal_jco()(length(unique(melted_df$Group)))
names(x_cols) = unique(melted_df$Group)
ggplot(melted_df, ...   theme(axis.text.x = element_text(colour = x_cols))

I would like to add a legend to the plot (if possible, outside the plot), that explains the colouring of the x axis labels.

Thanks in advance for the help!

EDIT:

melted_df dataframe looks like this: enter image description here

Here the full code:

#Generate color mapping
x_cols = pal_jco()(length(unique(melted_df$Group)))
names(x_cols) = unique(melted_df$Group)
melted_df$mycolors = sapply(as.character(melted_df$Group), function(x) x_cols[x])

#Plot
ggplot(melted_df, aes(fill=variable, y=value, x=fct_inorder(id)))   
  geom_bar(position="stack", stat = "identity")   ggtitle("Barplot")  
   theme_bw()  
   xlab("samples")   ylab("Counts")  
   theme(axis.title.y=element_text(size=10), axis.title.x=element_text(size=10),
        plot.title = element_text(face = "bold", size = (15), hjust = 0.5),
        axis.text.x = element_text(distinct(samples_melt[c("id", "mycolors")])$mycolors))  
    guides(fill=guide_legend(title="Columns"))

CodePudding user response:

In the absence of a reproducible example, here is how you might do it with the built-in iris data set:

library(ggplot2)

ggplot(iris, aes(Species, Sepal.Length))  
  stat_summary(fun = mean, geom = "col", aes(fill = Species))  
  geom_point(aes(color = Species), alpha = 0, key_glyph = draw_key_text)  
  theme_bw(base_size = 20)  
  labs(color = "")  
  guides(color = guide_legend(override.aes = list(alpha = 1, size = 8)))  
  theme(axis.text.x = element_text(color = scales::hue_pal()(3), face = 2))

enter image description here

CodePudding user response:

I addressed the issue using Legend() constructor, provided by ComplexHeatmap library.

I first used the code provided above under the EDIT section, and then I added the following code in order to draw an additional legend explaining the x-axis colouring.

lgd = Legend(labels = names(x_cols), title = "Group", labels_gp = gpar(fontsize = 8), nrow = 1, legend_gp = gpar(fill = x_cols))
draw(lgd, x = unit(1.8, "cm"), y = unit(0.3, "cm"), just = c("left", "bottom"))
  • Related