как изменить масштаб geom_tile для очень маленьких значений? - PullRequest
0 голосов
/ 06 августа 2020

У меня есть фрейм данных, содержащий некоторые сравнения, и значение представляет собой сходство между объектами. У меня есть реальный объект по сравнению с некоторыми случайными, что привело к очень небольшому сходству. Кроме того, я сравнил случайные объекты со случайными, что привело к более высокому уровню сходства. На этом этапе я хочу собрать все вместе и построить тепловую карту. Проблема в том, что очень маленькие значения сходства, которые я хочу выделить, имеют тот же цвет, что и не такие уж маленькие значения из случайного-случайного сравнения. Конечно, это проблема масштаба, но я не знаю, как управлять цветовой шкалой. Следующий код создает тепловую карту, которая действительно показывает проблему. Здесь первый столбец имеет желтый цвет sh, и это нормально, но это тот же цвет, что и у других плиток, которые, с другой стороны, имеют более высокие несопоставимые значения. Как раскрасить плитку в соответствии с фактическим масштабом?

Код:

set.seed(131)

#number of comparisons in the original data: 1 value versus n=10
n <- 10
#generate real data (very small values)
fakeRealData <- runif(n, min=0.00000000000001, max=0.00000000000002)

#and create the data structure
realD <- cbind.data.frame(rowS=rep("fakeRealData", n), colS=paste("rnd", seq(1, n, by=1), sep=" "), Similarity=fakeRealData, stringsAsFactors=F)

#the same for random data, n=10 random comparisons make for a n by n matrix
rndN <- n*n
randomData <- data.frame(matrix(runif(rndN), nrow=n, ncol=n))

rowS <- vector()
#for each column of randomData
for (r in seq(1, n, by=1)) {
    #create a vector of the first rowname, then the second, the third, etc etc which is long as the number of columns
    rowS <- append(rowS, rep(paste("rnd", r, sep=" "), n))
}

#and create the random data structure
randomPVs <- cbind.data.frame(rowS=rowS, colS=rep(paste("rnd", seq(1, n, by=1), sep=" "), n), Similarity=unlist(randomData), stringsAsFactors=F)

#eventually put everything together
everything <- rbind.data.frame(randomPVs, realD)

#and finally plot the heatmap
heaT <- ggplot(everything, aes(rowS, colS, fill=Similarity)) + 
    geom_tile() +
    scale_fill_distiller(palette = "YlGn", direction=2) +
    theme_bw() + 
    theme(axis.text.x = element_text(angle = 45, hjust = 1))+
    xlab("")+
    ylab("")

plot(heaT)

1 Ответ

1 голос
/ 06 августа 2020

Вот три подхода:

Добавьте geom_text к вашему графику, чтобы отображать значения при небольших цветовых различиях.

heaT <- ggplot(everything, aes(rowS, colS)) + 
  geom_tile(aes(fill=Similarity)) +
  scale_fill_distiller(palette = "YlGn", direction=2) +
  geom_text(aes(label = round(Similarity, 2))) +
  theme_bw() + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  xlab("") +
  ylab("")

heat map with text labels

Use the values argument to set a nonlinear scale to scale_fill_distiller. I added an extra break point at 0.01 to the otherwise linear scale to accentuate the difference between 0 and small nonzero numbers. I let the rest of the scale linear.

heaT 

enter image description here

Transform your scale as Richard mentioned in the comments. Note that this will mess with the values in the legend, so either rename it or hide it.

heaT 

введите описание изображения здесь

Попробуйте комбинации этих подходов и посмотрите, что вам понравится.

...