First of all, when you post a question involving plotting, it's extremely helpful if you provide a minimal, reproducible example. Otherwise it's difficult to give specific coding suggestions or you just make the person answering your question do unnecessary work. I'll try to saved time by taking an example from the ?heatmap.2
help page
data(mtcars)
x <- as.matrix(mtcars)
library(gplots)
xx <- heatmap.2(x)
Here we make sure to save the results of the plotting command to a variable. This stores the dendrograms for the rows and columns. You can get at the labels with
head(finalrownames<-labels(xx$rowDendrogram))
# [1] "Maserati Bora" "Chrysler Imperial" "Lincoln Continental"
# [4] "Cadillac Fleetwood" "Hornet Sportabout" "Pontiac Firebird"
head(finalcolnames<-labels(xx$colDendrogram))
# [1] "cyl" "am" "vs" "carb" "wt" "drat"
here i took the head()
just to keep the output to a minimal length.