【问题标题】:How to fill the plot area using geom_raster or geom_tile如何使用 geom_raster 或 geom_tile 填充绘图区域
【发布时间】:2012-05-08 16:07:36
【问题描述】:

我有以下数据框:

 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 轴以填充绘图空间。

【问题讨论】:

  • 看起来geom_raster(hpad=0, vpad=0) 是为了做你想做的事,但我测试了它,它对情节没有影响。也许它还没有实现?
  • 只是为了好玩 :-),尝试scale_y_discrete(expand = c(-1, -1)) 或其他一些值,看看是否/如何调整 y 比例。确保您在绘图空间与绘图窗口边距等方面没有遇到其他限制。
  • 试过 scale_y_discrete(expand = c(-1, -1))。没有运气。

标签: r ggplot2


【解决方案1】:

更新在最新版本的 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")

# 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()

【讨论】:

  • 谢谢桑迪。数字版本适用于我正在尝试做的事情。知道为什么它不适用于离散变量吗?
  • @Mike,没有想法。但这可能是一个错误,已在开发版本中修复。我刚刚使用开发版本运行了您的代码,并且瓷砖填充了 y 轴上的空间。开发版本将很快发布 - see here。如果您等不及 0.9.1 版,请see here 获取有关安装开发版的说明。
  • @Mike,我的意思是“ggplot2的开发版”。
  • ggplot2 0.9.1 现在在起重机上。升级,一切都应该很好。
  • plot 怎么样?如果我想用plot 来做呢?
猜你喜欢
  • 2017-09-09
  • 1970-01-01
  • 2020-02-14
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-20
  • 1970-01-01
相关资源
最近更新 更多