gpt4 book ai didi

r - 为绘图制作 2D 图例 - 双变量等值线图

转载 作者:行者123 更新时间:2023-12-01 00:48:32 27 4
gpt4 key购买 nike

我一直在玩双变量等值线图,并且一直在研究如何创建类似于 Joshua Stevens 的图例的二维图例。此处显示:

enter image description here

为了说明这一挑战,我们不需要使用 map 。下面的代码就足够了:

#test desired legend appearance
library(ggplot2)
library(reshape2)
#use color scheme shown here http://www.joshuastevens.net/cartography/make-a-bivariate-choropleth-map/
bvColors=c("#be64ac","#8c62aa","#3b4994","#dfb0d6","#a5add3","#5698b9","#e8e8e8","#ace4e4","#5ac8c8")
legendGoal=melt(matrix(1:9,nrow=3))
test<-ggplot(legendGoal, aes(Var1,Var2))+ geom_tile(aes(fill = as.factor(value)))
test<- test + scale_fill_manual(name="Var1 vs Var2",values=bvColors,drop=FALSE)
test

它创建了一个看起来像我想要的图例的图,但当然图例是所有级别的垂直条。我希望图例看起来像情节本身。有没有办法做到这一点?谢谢!

最佳答案

#test desired legend appearance
library(ggplot2)
library(reshape2)
#use color scheme shown here http://www.joshuastevens.net/cartography/make-a-bivariate-choropleth-map/
bvColors=c("#be64ac","#8c62aa","#3b4994","#dfb0d6","#a5add3","#5698b9","#e8e8e8","#ace4e4","#5ac8c8")
melt(matrix(1:9,nrow=3))
legendGoal=melt(matrix(1:9,nrow=3))
test<-ggplot(legendGoal, aes(Var2,Var1,fill = as.factor(value)))+ geom_tile()
test<- test + scale_fill_manual(name="More Var2 -->",values=bvColors,drop=FALSE)
test<-test+guides(fill = guide_legend(nrow = 3))
test<-test + theme(legend.text=element_blank())

test

enter image description here

唯一剩下的技巧是找到一种方法,在图例的一侧添加一些垂直的“More Var1 -->”。这是一个丑陋的方法:
test<-ggplot(legendGoal, aes(Var2,Var1,fill = as.factor(value)))+ geom_tile()
test<- test + scale_fill_manual(name="More Var2 -->",values=bvColors,labels=c("","","","","","","More","Var 1"," v "))
test<-test+guides(fill = guide_legend(nrow = 3))
#test<-test + theme(legend.text=element_blank())

test

但是,正如 zx 所示,使用 cowplot 包扩展 ggplot2 是完整的解决方案:
#test desired legend appearance
library(ggplot2)
library(cowplot)
library(reshape2)
#use color scheme shown here http://www.joshuastevens.net/cartography/make-a-bivariate-choropleth-map/
bvColors=c("#be64ac","#8c62aa","#3b4994","#dfb0d6","#a5add3","#5698b9","#e8e8e8","#ace4e4","#5ac8c8")
melt(matrix(1:9,nrow=3))
legendGoal=melt(matrix(1:9,nrow=3))
test<-ggplot(legendGoal, aes(Var2,Var1,fill = as.factor(value)))+ geom_tile()
test<- test + scale_fill_manual(name="",values=bvColors)
test<-test+guides(fill = guide_legend(nrow = 3))
test<-test + theme(legend.text=element_blank())
test<-ggdraw(test) + draw_text(text = "More Var 2 -->",x=0.91,y=0.58)
test<-ggdraw(test) + draw_text(text = "More Var 1 -->",x=0.84,y=0.5,angle=270)
test

enter image description here

只是为了好玩,这是我用这种技术制作的 map :
NYC Pre-K Seats

关于r - 为绘图制作 2D 图例 - 双变量等值线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32749889/

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