tafelplankje
tafelplankje

Reputation: 583

R: ggplot2, replace Y axis labels to geom_tile

I used the code provided in R: How do I display clustered matrix heatmap (similar color patterns are grouped) succesfully, however im not able to replace the Y-axis with text-labels, is this possible?

library(reshape2)
library(ggplot2)

# Create dummy data
set.seed(123)
df <- data.frame(
  a = sample(1:5, 25, replace=TRUE),
  b = sample(1:5, 25, replace=TRUE),
  c = sample(1:5, 25, replace=TRUE)
)

# Perform clustering
k <- kmeans(df, 3)

# Append id and cluster
dfc <- cbind(df, id=seq(nrow(df)), cluster=k$cluster)

# Add idsort, the id number ordered by cluster 
dfc$idsort <- dfc$id[order(dfc$cluster)]
dfc$idsort <- order(dfc$idsort)

# use reshape2::melt to create data.frame in long format
dfm <- melt(dfc, id.vars=c("id", "idsort"))

ggplot(dfm, aes(x=variable, y=idsort)) + geom_tile(aes(fill=value))

Upvotes: 0

Views: 4109

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98459

You can use scale_y_continuous() to set breaks= and then provide labels= (for example used just letters). With argument expand=c(0,0) inside scale_... you can remove grey area in plot.

ggplot(dfm, aes(x=variable, y=idsort)) + geom_tile(aes(fill=value))+
  scale_x_discrete(expand=c(0,0))+
  scale_y_continuous(expand=c(0,0),breaks=1:25,labels=letters[1:25])

Upvotes: 3

Related Questions