gpt4 book ai didi

r - 如何将边界框添加到ggplot2热图中的特定区域?

转载 作者:行者123 更新时间:2023-12-04 11:07:48 26 4
gpt4 key购买 nike

我使用 here 中的示例.我的问题是如何向此热图添加特定的边界框,例如在左上角的四个图 block 中添加一个红线框?

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

enter image description here

最佳答案

一种快速而肮脏(一些硬编码)的可能性是使用 geom_rect ,其中位置由要与框绑定(bind)的 x 和 y 变量的级别的数值给出,加上/减去偏移量。

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)

enter image description here

一个不那么硬编码的版本:
# 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)

关于r - 如何将边界框添加到ggplot2热图中的特定区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22024641/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com