ggplot2以轴为单位指定点大小 [英] ggplot2 specify point size in axis units

查看:160
本文介绍了ggplot2以轴为单位指定点大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个简单的数据集中绘制一个矩形内的大点的图.我可能希望在不同的方面显示多个结果.问题在于,矩形的大小(使用geom_rect)是以轴为单位定义的,而geom_pointsize自变量是以某些其他单位定义的.因此,矩形的点的相对大小会根据构面的数量而变化:

I want to do a plot with large points inside a rectangle from a simple dataset. There are potentially multiple results that I want to display in different facets. The problem is that the size of the rectangle (using geom_rect) is defined in axis units while the size argument of geom_point is in some other units. Thus, the relative size of the points wrt the rectangle changes depending on the number of facets:

data<-data.frame(y=1:3,
                 facet=factor(1:3),
                 x=rep(1,3))

testplot<-function(data){
  p<-ggplot(data,aes(x=x,y=y,color=y))
  p<-p+facet_grid(.~facet)
  p<-p+scale_x_continuous(limits=c(0.5,1.5))
  p<-p+scale_y_continuous(limits=c(0.5,3.5))
  p<-p+geom_rect(xmin=0.85,xmax=1.15,ymin=0.74,ymax=3.25)
  p<-p+geom_point(size=50)
  return(p)
}

p1<-testplot(subset(data,facet=="1"))
p2<-testplot(data)

我的问题是,是否可以按轴单位缩放绝对点的大小,以便p1和p2的点和矩形的相对大小相同,而与图形中的构面数量无关.

My question is, if I can scale the absolute point size in axis units, so that the relative size of points and the rectangle is identical for p1 and p2, independent of the number of facets in the graph.

推荐答案

使其相当简单,半径r相对于坐标比例缩放(因此,如果要使用圆,则使用coord_fixed()很重要).

ggforce makes this fairly straight forward, the radius r is scaled relative to the coordinate scales (therefore important to use coord_fixed() if you want circles).

示例:

library(ggplot2)
library(ggforce)

##sample data frame
grid_df = data.frame(x = 1:5, y = rep(1,5), r = seq(0.1, 0.5, 0.1), fill = letters[1:5])

带有空圆圈

ggplot() + 
geom_circle(data = grid_df, mapping = aes(x0 = x,  y0 = y, r = r)) + 
coord_fixed()

具有实心圆和固定"填充(在aes之外)

ggplot() + 
geom_circle(data = grid_df, mapping = aes(x0 = x,  y0 = y, r = r), fill = 'black') + 
coord_fixed()

具有实心圆并基于变量填充(在aes内部)

ggplot() + 
geom_circle(data = grid_df, mapping = aes(x0 = x,  y0 = y, r = r, fill = fill)) + 
coord_fixed()

这篇关于ggplot2以轴为单位指定点大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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