如何将边界框添加到ggplot2热图中的特定区域? [英] How to add bounding box to a specific area in ggplot2 heatmap?

查看:194
本文介绍了如何将边界框添加到ggplot2热图中的特定区域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从此处.我的问题是如何向此热图添加特定的边界框,例如在左上方的四个图块中添加红线框?

I use an example from here. My question is how can I add a specific bounding box to this heatmap, such as add a red line box to the top left four tiles?

require(ggplot2)
require(reshape)
require(scales)

mydf <- data.frame(industry = c('all industries','steel','cars'), 
    'all regions' = c(250,150,100), americas = c(150,90,60), 
     europe = c(150,60,40), check.names = FALSE)
mydf

mymelt <- melt(mydf, id.var = c('industry'))
mymelt

ggplot(mymelt, aes(x = industry, y = variable, fill = value)) +
    geom_tile() + geom_text(aes(fill = mymelt$value, label = mymelt$value))

推荐答案

一种快速而肮脏的方法(使用一些硬编码)是使用geom_rect,其中位置由x和与框绑定的y个变量,加上/减去偏移量.

A quick and dirty (some hard-coding) possibility is to use geom_rect, where the positions are given by the numerical values of the levels of x and y variables to be bound with a box, plus/minus an offset.

ggplot(mymelt, aes(x = industry, y = variable, fill = value, label = value)) +
  geom_tile() +
  geom_text() +
  geom_rect(aes(xmin = 1 - 0.5, xmax = 2 + 0.5, ymin = 2 - 0.5, ymax = 3 + 0.5),
               fill = "transparent", color = "red", size = 1.5)

一个不太硬编码的版本:

A less hard-coded version:

# convert x and y variables to factors
ind <- as.factor(mymelt$industry)
vars <- as.factor(mymelt$variable)

# numeric version of the levels to be bound by a box
xmin <- unique(as.numeric(ind[ind == "all industries"]))
xmax <- unique(as.numeric(ind[ind == "cars"]))

ymin <- unique(as.numeric(vars[vars == "americas"]))
ymax <- unique(as.numeric(vars[vars == "europe"]))

# set offset
offset <- 0.5

ggplot(mymelt, aes(x = industry, y = variable, fill = value, label = value)) +
  geom_tile() +
  geom_text() +
  geom_rect(aes(xmin = xmin - offset,
                xmax = xmax + offset,
                ymin = ymin - offset,
                ymax = ymax + offset),
            fill = "transparent", color = "red", size = 1.5)

这篇关于如何将边界框添加到ggplot2热图中的特定区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆