简体   繁体   English

创建具有离散颜色的地图

[英]Create map plot with discrete colors

I have just started to use ggplot2 and have created a map overlaid with data represented by a continuous color map.我刚刚开始使用 ggplot2 并创建了一个地图,上面覆盖着由连续彩色地图表示的数据。 The data runs from 0.205 to 0.756.数据从 0.205 到 0.756。 However, I would like to plot the data with 'n' discrete colors, and with the mid point at 0.5.但是,我想用“n”个离散颜色绘制数据,中点为 0.5。

I have modified the relevant part of my code to the following:我已将代码的相关部分修改为以下内容:

...
df %>% # dataframe
mutate(value_cut = cut_interval(value, n = 6)) %>%
ggplot() -> gg

gg <- gg + geom_polygon(aes(x = long, y = lat, group = group,
                            fill = value_cut), size = 0.25, color = NA)
gg <- gg + viridis::scale_fill_viridis(discrete = TRUE,direction=-1)
...
print(gg)

which generates the following plot:生成以下图: 具有离散数据级别的映射

It is almost there, but I would like to be able to specify an 'even' number of unique colors and have the mid-point set at 0.5.它几乎就在那里,但我希望能够指定一个“偶数”数量的独特颜色,并将中点设置为 0.5。 I have tried a number of different approaches but, usually end up with errors.我尝试了许多不同的方法,但通常以错误告终。

Any help appreciated.任何帮助表示赞赏。

I am including my answer in case it helps someone in future.我包括我的答案,以防将来对某人有所帮助。

Following advice from ulfelder , I used R functions cut() and scale_fill_manual() , when the relevant code becomes根据ulfelder建议,我使用了 R 函数cut()scale_fill_manual() ,当相关代码变为

...
df %>%
  mutate(value_cut = cut(value, breaks=c(0.2,0.35,0.5,0.65,0.8))) %>%
  ggplot() -> gg

# Create the coloured map using the ggplot2 package
# color=NA omits demarcation lines between constituencies
gg <- gg + geom_polygon(aes(x = long, y = lat, group = group,
                            fill = value_cut),
                        size = 0.25, color = NA)
cols <- c("yellow","gold","lightblue","royalblue")
gg <- gg + scale_fill_manual(values = cols)
...
print(gg)

which generates the following plot:生成以下图:

在此处输入图片说明

as required.按要求。

More discrete colors can be readily achieved by increasing the number of breaks when calling the cut() function, and increasing the number of colors in the cols array.通过在调用cut()函数时增加breaks次数并增加cols数组中的颜色数量,可以轻松实现更离散的颜色。

Many thanks to ulfelder for the excellent and prompt advice.非常感谢ulfelder提供的出色而及时的建议。

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

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