如何使用geom_raster或geom_tile填充绘图区域

时间:2012-05-08 16:07:36

标签: r ggplot2

我有以下数据框:

 id  variable   value
 ID1    1A      91.98473282
 ID1    2A      72.51908397
 ID1    2B      62.21374046
 ID1    2D      69.08396947
 ID1    2F      83.39694656
 ID1    2G      41.60305344
 ID1    2H      63.74045802
 ID1    9A      58.40839695
 ID1    9C      61.10687023
 ID1    9D      50.76335878
 ID1    9K      58.46183206

我正在使用ggplot2生成包含数据的热图:

     ggplot(data, aes(variable, id)) +
              geom_raster(aes(fill = value)) + 
              scale_fill_gradient(low = "white",
              high = "steelblue")

情节如下: http://dl.dropbox.com/u/26998371/plot.pdf

我希望瓷砖填充y轴上的绘图空间,而不是在上方和下方留下空格。

我确信有一个简单的答案。任何帮助将不胜感激。

scale_y_discrete(expand = c(0,0))不适用于y轴,但scale_x_discrete(expand = c(0,0))将在x轴上工作以填充绘图空间。

1 个答案:

答案 0 :(得分:5)

更新在最新版本的ggplot2中,问题似乎已得到解决。

id因素中只有一个级别有关。将id因子更改为数字,或更改id因子,使其具有两个级别,然后切片填充空格。此外,coord_equal()原始id因素会给出一个很长的狭窄情节,但会再次填补空间。

## Your data
df = read.table(text = "
id  variable   value
ID1    1A      91.98473282
ID1    2A      72.51908397
ID1    2B      62.21374046
ID1    2D      69.08396947
ID1    2F      83.39694656
ID1    2G      41.60305344
ID1    2H      63.74045802
ID1    9A      58.40839695
ID1    9C      61.10687023
ID1    9D      50.76335878
ID1    9K      58.46183206", header = TRUE, sep = "")

library(ggplot2)

 # Change the id factor
 df$id2 = 1                   # numeric
 df$id3 = c(rep("ID1", 5), rep("ID2", 6))      # more than one level

 # Using the numeric version
 ggplot(df, aes(variable, id2)) +
          geom_raster(aes(fill = value)) + 
          scale_y_continuous(breaks = 1, labels = "ID1", expand = c(0,0)) + 
          scale_x_discrete(expand = c(0,0)) +
          scale_fill_gradient(low = "white",
          high = "steelblue")

enter image description here

# Two levels in the ID factor
ggplot(df, aes(variable, id3)) +
          geom_tile(aes(fill = value)) + 
          scale_fill_gradient(low = "white",
          high = "steelblue") 

# Using coord_equal() with the original id variable
ggplot(df, aes(variable, id)) +
          geom_tile(aes(fill = value)) + 
          scale_fill_gradient(low = "white",
          high = "steelblue") +
          coord_equal()
相关问题