rpositionlegendtitletmap

How to combine and position title and legend in tmap in R?


I am struggling to place the title inside the frame of the legend, but on top of the legend and not below. Any guidance or working examples would be greatly appreciated! Thank you. The online help isn't very helpful, as many suggestions refer to versions prior to v4.

require(tmap)
tm_shape(World) +
    tm_polygons(
        fill = "HPI",
        fill.legend = tm_legend(
            bg.color = "grey80",
            position = tm_pos_in()
        ))+
    tm_title_in( text = "My Title",
                             bg.color = "grey80")

Solution

  • You can use position = tm_pos_on_top() in the tm_title_in() call:

    tm_shape(World) +
      tm_polygons(
        fill = "HPI",
        fill.legend = tm_legend(
          bg.color = "grey80",
          position = tm_pos_in()
        )) +
      tm_title_in( text = "My Title",
                 bg.color = "grey80",
                 position = tm_pos_on_top())
    

    enter image description here


    Previous answer

    Try adding the map title and legend title together, separated by a new line \n

    tm_shape(World) +
      tm_polygons(
        fill = "HPI",
        fill.legend = tm_legend(
          title="My map title\nHPI",
          bg.color = "grey80",
          position = tm_pos_in()
        ))
    

    enter image description here


    Another previous answer:

    Put the legend position explicitly in tm_legend.

    tm_shape(World) +
      tm_polygons(
        fill = "HPI",
        fill.legend = tm_legend(
          bg.color = "grey80",
          position = tm_pos_in(pos.h = 0.03, pos.v = 0.85)
        )) +
      tm_title_in(text = "My Title",
               bg.color = "grey80")
    

    enter image description here