突出散点图的特定区域中ggplot(Highlighting particular regions

2019-07-30 23:56发布

我需要讨论的散点图,想指的是情节的特定区域。 有没有什么办法,以情节的“亮点”特定部分? 也许盒和标签,如下?

set.seed(1410)
dsmall<-diamonds[sample(nrow(diamonds), 100), ]
df<-data.frame("x"=dsmall$carat, "y"=dsmall$price)

p <-ggplot(df, aes(x, y)) 
p <- p + geom_point(alpha=2/10, shape=21, fill="blue", colour="black", size=5)

Answer 1:

对于一个区域,它是最容易使用的annotate有,第一rect ,然后text

p + annotate("rect", xmin=1.5, xmax=2.5, ymin=12500, ymax= 18000, 
             fill=NA, colour="red") +
    annotate("text", x=1.75, y=17000, label="Region A", size=8)


对于多个地区,可以把数据转换成数据帧和使用geom_textgeom_rect

regions <- data.frame(
  xmin=c(1.5, 1, 0),
  xmax=c(2.5, 2, 1),
  ymin=c(12500, 5000, 0),
  ymax=c(17500, 12500, 5000),
  x   =c(2, 1.5, 0.5),
  y   =c(15000, 7500, 2500),
  lab = paste("Region", LETTERS[1:3])
)

p + 
  geom_rect(data=regions, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax), 
            fill=NA, colour="red") +
  geom_text(data=regions, aes(x=x, y=y, label=lab)) 



文章来源: Highlighting particular regions of a scatterplot in a ggplot
标签: r ggplot2