Legend of a raster map with categorical data

后端 未结 2 2077
庸人自扰
庸人自扰 2020-12-03 03:57

I would like to plot a raster containing 4 different values (1) with a categorical text legend describing the categories such as 2 but with colour boxes:

I\'ve tried

2条回答
  •  臣服心动
    2020-12-03 04:20

    By default, the colours used in a raster-plot are generated by rev(terrain.colors()) (see ?raster::plot). You can use this to re-create that sequence of 4 colours for your legend - or choose a random sequence of colours:

    my_col = rev(terrain.colors(n = 4))
    # my_col = c('beige','red','green','blue')
    

    First plot the map using the colour sequence. legend = FALSE gets rid of the standard colour bar:

    plot(my_raster, legend = FALSE, col = my_col)
    

    Add a custom legend to the bottom left. Use the fill argument to generate coloured boxes:

    legend(x='bottomleft', legend = c("land", "ocean/lake", "rivers", "water bodies"), fill = my_col)
    

提交回复
热议问题