MYjx
MYjx

Reputation: 4427

add multiple legends to a heatmap in R

My question is that I want to add the categorical variables' legends onto the graph but somehow when I used "topright", it did not work for me (see the image below). Basically my idea is to fill the blank area with the legends for my categorical variables on the side of the heatmap. My codes look like

heatmap.3(performance, Colv =NA,RowSideColors=row_annotation,col=my_palette)

par(lend = 1)           # square line ends for the color legend
legend("topright",      # location of the legend on the heatmap plot
       legend = c("category1", "category2", "category3"), # category labels
       col = c("gray", "blue", "black"),  # color key
       lty= 1,             # line style
       lwd = 10            # line width
      )

Also I want to put multiple legend onto the plot but don't know how to specify their positions using x and y as there are no coordinates in my plot.

Thank you so much! enter image description here

Upvotes: 0

Views: 5039

Answers (1)

warship
warship

Reputation: 3024

A simple fix to your problem would be to use the option inset=# (where # is some floating point number with a comma after it) following your "topright" specification after its respective comma, which would indicate how to place your legend relative to your graph.

Instead of specifying the default position "topright", perhaps you may want to try restructuring your code in a more personally customized manner, namely utilizing an x-y axis approach, such as for instance use :

dev.new(xpos=#,ypos=#)

Or you may also consider using:

legend.position=c(#,#)

Try these options, even though you say you have no access to coordinates, which is rare for graphical utilities in R, but may well be a future edit to heatmap.3. You could also use a fancy R utility called locator(1) to point and click with your mouse where you want to see your legend.

In general, the legend option is formally defined as:

legend(location, title, legend, ...)

If you have any more questions about the legend utility in R, please type in help(legend) in your R command line (in R Studio, for instance, if you use that).

To address your question on multiple legends, please consult: Plotting multiple legends

Upvotes: 1

Related Questions