简体   繁体   English

使用ggplot进行气泡图的自定义图例

[英]Custom legend for bubble plot using ggplot

I have a dataframe which contains a spatial variable with simulated and observed values. 我有一个数据框,其中包含具有模拟值和观察值的空间变量。

df <- data.frame(sim = sample((20:30),10),
                 obs = sample(25:40,10),
                 long = rnorm(10,10,8),
                 lat = rnorm(10,30,15))

I have plotted a spatial bubble plot using the following code. 我已经使用以下代码绘制了空间气泡图。

ggplot() +
geom_polygon(data = shp, aes(x = long, y = lat, group = group),
             col = "black", lwd = 0.8, fill = "slategray1",
             alpha = 0.5) +
coord_cartesian() + 
geom_point(data = df, aes(x = long, y = lat, group = sim, size = sim), col = "red", alpha = 0.5) +
geom_point(data = df, aes(x = long, y = lat, group = obs, size = obs), col = "blue", alpha = 0.5) +
scale_size_continuous(range = c(10,20)) +
coord_map(xlim = c(-1, 22), ylim = c(10, 45))

The output of the above code is in the image. 上面代码的输出在图像中。 What I want to show in the plot is the difference between the simulated and observed data which is done perfectly. 我想在图中显示的是模拟数据和观察到的数据之间的差异,可以很好地完成。 Now, I want to show two different legend for the two variable sim and obs which will be red and blue color legend respectively. 现在,我想为两个变量simobs显示两个不同的图例,分别是红色和蓝色图例。 Also I want to show the magnitude of the variable in the legend but not as the varying size of bubbles, but in some different way. 我也想在图例中显示变量的大小,而不是显示气泡大小的变化,而是以某种不同的方式显示。 Something like given here . 有点像这里给的。 Can someone help me in achieving this? 有人可以帮助我实现这一目标吗?

在此处输入图片说明

Would it be okay with you to leave the size of the bubble as they are? 可以保留气泡的大小吗,可以吗?

    df<-data.frame(sim=sample((20:30),10),obs=sample(25:40,10),long=rnorm(10,10,8),lat=rnorm(10,30,15))
shp <- df %>%
  gather(group, value, -long, -lat)

ggplot()+
  geom_polygon(data = df, aes(x = long, y = lat),col="black",lwd=0.8,fill="slategray1",alpha=0.5)+
  coord_cartesian()+
  geom_point(data=shp,aes(x=long,y=lat,group=group,size=value, fill = group, color = group),alpha=0.5)

在此处输入图片说明

Explanation 说明

To get different colors for the groups, gather obs and sim into one column and specify this column as the colour aesthetic. 要为组获得不同的颜色,请将obssim收集到一列中,并将此列指定为颜色美观。 blue and red are the default colors ggplot2 assign for variables with two levels. blueredggplot2为具有两个级别的变量分配的默认颜色。 So I deleted one geom_point and used the long form of your data instead for the remaining geom_point . 因此,我删除了一个geom_point并使用数据的长格式代替了其余的geom_point

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM