【问题标题】:R Colorize departments of a france map according to the values of a vectorR根据向量的值对法国地图的部门进行着色
【发布时间】:2017-11-06 02:23:47
【问题描述】:

嗨,我怎样才能用 R 制作这样的地图?

给出这张地图的代码,但我没有数据:

 library(RColorBrewer)
 library(classInt)
 library(maptools)
 plotvar <- fecondite$fecond1524
 nclr <- 4
 plotclr <- brewer.pal(nclr,"PuOr")
 plotclr <- plotclr[nclr:1] # r´eordonne les couleurs
 class <- classIntervals(plotvar, nclr, style="equal")
 colcode <- findColours(class, plotclr)
 plot(departements,col=colcode)
 locator(n=1) #sert `a trouver les coordonn´ees
 du point o`u vous souhaitez placer la l´egende
 legend(166963,6561753,legend=names(attr(colcode,"table")),
 fill=attr(colcode, "palette"), cex=0.6, bty="n")

事实上我想知道:例如,一个向量包含从 1 到 1000 的数字,这些数字与部门有关如何为每个间隔 [1, 100]、[100, 500]、[500] 分配不同的颜色, 1000 ] ?

【问题讨论】:

  • 你有示例代码吗?
  • 我只有提供此地图的代码,但我没有数据,所以我无法使用此代码对其进行测试
  • 你想要随机着色?
  • 不,我不想要随机着色,我想通过一个向量的值来着色,例如一个包含每个部门的表面的向量,带有类似于图片的图例。

标签: r colors maps


【解决方案1】:

这就是你要找的吗?

library(raster)

fr <- getData(country='France',level=2)
#plot(fr)

# random terrain colors
fr$col <- terrain.colors(256)[floor(runif(length(fr),0,255))]

# less random
#fr$col <- terrain.colors(length(fr))

plot(fr,col=fr$col)

编辑:

您可以访问fr$NAME_2 下的部门名称,然后相应地分配您的颜色:

color_df <- data.frame(Dep=fr$NAME_2,color=sample(colors(distinct=T),length(fr),replace = F))

fr$col <- color_df$color

plot(fr,col=fr$col)

print(color_df)

这个例子有点傻,因为它又是随机颜色。但是您可以为每个部门分配渐变或任何其他颜色值。

编辑 2:突出显示单个部门

library(raster)

fr <- getData(country='France',level=2)

fr$col[fr$NAME_2 == 'Hautes-Alpes'] <- 'red'

plot(fr,col=fr$col)

编辑 3:按假生育组绘制

library(raster)

fr <- getData(country='France',level=2)

# fertility classes
classes <- c('0-1.4','1.4-2.4','2.5-3')

#fake data
fr$fertility <- sample(seq(1,3,0.1),length(fr),replace = T)

# assign groups
fr$fertgroups <- round(fr$fertility) 

# assign corresponding colors (red = low, yellow = mid, green = high)
fr$cols <- c('red','yellow','green')[fr$fertgroups]

#plot
plot(fr,col=fr$cols)

或者有 4 个类:

library(raster)

fr <- getData(country='France',level=2)

classes <- c('0-1','1-1.5','1.5-2','2-3')

fr$fertility <- sample(seq(1,3,0.1),length(fr),replace = T)

fr$fertgroups[fr$fertility <=1] <-1 
fr$fertgroups[fr$fertility > 1 & fr$fertility <=1.5] <-2 
fr$fertgroups[fr$fertility > 1.5 & fr$fertility <=2] <-3 
fr$fertgroups[fr$fertility > 2 & fr$fertility <=3] <- 4 

fr$cols <- c('red','orange','yellow','green')[fr$fertgroups]

plot(fr,col=fr$cols)

【讨论】:

  • 不抱歉,您的代码给了我一张完全没有颜色的地图
  • 是的,行得通^^对不起,我的错,事实上我不想要随机着色我想用一个向量的值着色,例如一个包含每个部门表面的向量,其图例类似于图片。
  • 查看我的编辑...这真的取决于您想要哪种颜色。但是由于您已经在 fr 对象中拥有部门名称,因此您可以使用任何您喜欢的配色方案
  • 谢谢 ;) 你能给我看一个梯度分配给单个部门的例子吗?
  • 你的意思是一个部门是彩色的,其余的是白色的?
猜你喜欢
  • 1970-01-01
  • 2013-12-24
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多