Aan de slagGa gratis aan de slag

Adding neighborhood labels

The neighborhood labels are so long and big they are obscuring our data. Take a look at manhat_hoods$NTAName. You'll see some neighborhoods are really the combination of a couple of places. One option to make the names a little more concise is to split them into a few lines. For example, turning

Midtown-Midtown South

into

Midtown /
Midtown 
South

To do this, you can make use of the gsub() function in base R. gsub() replaces the first argument by the second argument in the strings provided in the third argument. For example, gsub("a", "A", x) replaces all the "a"s in x with "A".

You also might play with the size of the text to shrink the impact of the neighborhood names.

Deze oefening maakt deel uit van de cursus

Visualizing Geospatial Data in R

Cursus bekijken

Oefeninstructies

  • Create a new column name in manhat_hoods by using gsub() to replace all the spaces (" ") with newlines ("\n") in manhat_hoods$NTAName.
  • Update name in manhat_hoods by using gsub() to replace all the dashes ("-") with a forward slash then newline ("/\n") in manhat_hoods$name.
  • Edit your plot to map text to "name" and set the size to 0.5.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

library(tmap)

# gsub() to replace " " with "\n"


# gsub() to replace "-" with "/\n"


# Edit to map text to name, set size to 0.5
tm_shape(nyc_tracts_merge) +
    tm_fill(col = "estimate") +
  tm_shape(water) +
    tm_fill(col = "grey90") +
  tm_shape(manhat_hoods) +
    tm_borders() +
    tm_text(text = "NTAName")
Code bewerken en uitvoeren