nik nik - 3 months ago 11
R Question

how to make a heatmap with concrete values

I have a data like this

df<- structure(list(name = structure(c(2L, 12L, 1L, 16L, 14L, 10L,
9L, 5L, 15L, 4L, 8L, 13L, 7L, 6L, 3L, 11L), .Label = c("All",
"Bab", "boro", "bra", "charli", "delta", "few", "hora", "Howe",
"ist", "kind", "Kiss", "myr", "No", "TT", "where"), class = "factor"),
value = c(1.251, -1.018, -1.074, -1.137, 1.018, 1.293, 1.022,
-1.008, 1.022, 1.252, -1.005, 1.694, -1.068, 1.396, 1.646,
1.016)), .Names = c("name", "value"), class = "data.frame", row.names = c(NA,
-16L))


which looks like below

# name value
#1 Bab 1.251
#2 Kiss -1.018
#3 All -1.074
#4 where -1.137
#5 No 1.018
#6 ist 1.293
#7 Howe 1.022
#8 charli -1.008
#9 TT 1.022
#10 bra 1.252
#11 hora -1.005
#12 myr 1.694
#13 few -1.068
#14 delta 1.396
#15 boro 1.646
#16 kind 1.016


when I plot it

ggplot(df, aes(x = 1,y = name, fill = value)) +
geom_tile() +
ylab("")


it plots it randomly

enter image description here

but I want to have the same order as I have in my data. I also want to make the ylim smaller but I could not do. I appreciate any suggestion

Answer

The problem is your name factor has its levels sortet alphabetically. What you want to do is reorder the levels of name. Do this before the plot:

df$name <- factor(df$name, levels = df$name)

This will print the values as-is from bottom to top. For top-to-bottom ordering, use

df$name <- factor(df$name, levels = rev(df$name))

finally, setting "ylim" doesn't really make sense here. You might want to decrease the height of the canvas (e.g. by changing the size of the Plots pane in RStudio).