突出显示ggplot中散点图的特定区域 [英] Highlighting particular regions of a scatterplot in a ggplot

查看:1395
本文介绍了突出显示ggplot中散点图的特定区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要讨论一个散点图,并且想要参考该图的特定区域。有什么方法可以突出剧情的特定部分吗?也许有下面的框和标签?

  set.seed(1410)
dsmall< -diamonds [sample(nrow (钻石),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,color =black,size = 5)

注释 >,首先用 rect ,然后 text

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






对于多个地区,您可以将数据放入数据框中并使用 geom_text geom_rect
$ b $ (2.5,1,1),其中b

  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 =地区,aes(xmin = xmin,xmax = xmax,ymin = ymin,ymax = ymax),
fill = NA,color =red)+
geom_text(data = regions,aes(x = x,y = y,label = lab))


I need to discuss a scatter plot and would like to refer to particular regions of the plot. Is there any way to 'highlight' particular sections of the plot? Perhaps with boxes and labels as below?

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)

解决方案

For a single region, it's easiest to use annotate, first with rect, then 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)


For multiple regions, you can put the data into a data frame and use geom_text and geom_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)) 

这篇关于突出显示ggplot中散点图的特定区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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