簡體   English   中英

ggplot2在geom_raster中結合連續變量和離散變量

[英]ggplot2 combine continuous variable and discrete variable in geom_raster

我有一個包含兩種元素的 100 x 100 矩陣。 第一種是介於 0 和 100 之間的連續變量(實際上在程序中是離散的,但它們代表的是連續的,因此應該具有連續縮放的圖例),另一種類型是具有三個可能值(-1、-2、 -3)。 我在這個問題中使用了這個矩陣。

目標是制作連續變量的熱圖,同時區分具有離散負值的區域。 目前,我正在使用帶有 geom_raster 的 ggplot (請參閱此問題底部的代碼片段)來繪制以下熱圖。

當前熱圖

但是,頂部和右側的均勻灰色區域由負離散值組成,並且應該具有與圖的其他部分不同的顏色/圖案。 例如,這些區域應該是白色的,並帶有一個指示值的標簽(參見第二張圖片)。 有沒有辦法用ggplot做到這一點? 在理想情況下,該圖將有一個用於連續范圍的圖例和一個用於三個離散值的指南。

額外的問題:是否可以在邊界處畫一條線,即如果矩陣中的下一個元素具有不同的值,則畫一條線。 現在我通過僅繪制許多段來手動執行此操作(請參見第二個代碼片段),但這不是要走的路(而且我沒有成功將它與 ggplot 熱圖結合起來)。

在此處輸入圖像描述

第一個代碼片段(制作熱圖)

  minRate = 0;
  maxRate = 100;

  colnames(df) = NULL
  df = melt(df)
  colnames(df) = c("col", "row", "value")

  # geom_raster takes the center as input argument
  df[,"col"] = df[,"col"] - 0.5
  df[,"row"] = df[,"row"] - 0.5

  # Without labels
  ggplot(df, aes(x = col, y = row, fill = value)) + 
    geom_raster() + 
    theme_bw() +
    labs(fill="Rate (%)") + 
    theme(plot.margin=unit(c(3,3,3,2),"mm"), legend.position = "right") +
    scale_fill_gradient(low="black", high="white", limits=c(minRate, maxRate)) +
    scale_x_continuous("state 1", expand = c(0,0), limits=c(0,100)) + 
    scale_y_continuous("state 2", expand = c(0,0), limits=c(0,100))

第二個代碼片段(僅繪制邊界):

printPolicy <- function(df, title)
{
  n = nrow(df)

  plot(NA, xlim=c(0, n), ylim=c(0, n), 
       xlab="Machine 0", ylab="Machine 1", main=title,
       las=1, yaxs='i', xaxs='i')


  for (x0 in 1:(n-1))
  {
    for (x1 in 1:(n-1))
    {
      # Horizontal lines
      if (df[x0, x1] != df[x0+1, x1])
        segments(x1-1, x0, x1, x0)

      # Vertical lines
      if (df[x0, x1] != df[x0, x1+1])
        segments(x1, x0-1, x1, x0)
    }
  }
}

使用ggnewscale包相對容易做到這一點,請參見下面的示例。 假設datread.csv(the_data_you_posted)的輸出。

library(ggplot2)
library(ggnewscale)
dat <- as.matrix(dat)
dimnames(dat) <- NULL

mdat <- reshape2::melt(dat)

conti <- mdat[mdat$value >= 0,]
discr <- mdat[mdat$value < 0,]

ggplot(mapping = aes(Var1, Var2)) +
  geom_raster(data = conti, aes(fill = value), 
              hjust = 0, vjust = 0) +
  scale_fill_continuous() + # scale for continuous values need to be 
                            # defined before call to  new_scale_fill()
  new_scale_fill() +
  geom_raster(data = discr, aes(fill = as.factor(value)),
              hjust = 0, vjust = 0)

在此處輸入圖像描述

按照您認為合適的方式裝飾情節。

不幸的是,我不知道您的獎金問題的答案,但我很想知道是否有人有針對該問題的自動解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM