Cameron
Cameron

Reputation: 367

why does ggplot scale_colour_manual produce incorrect fill colours with shapefiles

Goal

I'm trying to create a map in ggplot of the French 2017 election results that fills each electorate with the colour of the winning party.

Problem

When I map the shapefile of French electorates with geom_sf, the fill argument doesn't recognise the hexadecimal values I feed it for each party's colour. Instead it assigns each party a new colour.

My map should be coloured like this correct party colours

But ggplot currently colours it like this incorrect party colours

Code

I have a shapefile of all french electorates, here, which in R looks like

df
   dept_circ party_2017 dept_nom                       geometry
1     001_01         LR      Ain POLYGON ((4.887938 46.41241...
2     001_02         LR      Ain POLYGON ((4.728168 45.94598...
3     001_03       LREM      Ain POLYGON ((5.570681 45.75369...
4     001_04       LREM      Ain POLYGON ((4.739192 46.04677...
5     001_05         LR      Ain POLYGON ((5.247852 45.94869...
6     002_01       LREM    Aisne POLYGON ((3.310763 49.68271...
7     002_02         LR    Aisne POLYGON ((3.055322 49.83207...
8     002_03         PS    Aisne POLYGON ((3.3149 49.95589, ...
9     002_04       LREM    Aisne POLYGON ((3.036076 49.3252,...
10    002_05       LREM    Aisne POLYGON ((2.957951 49.22691...

I created a corresponding set of colours for each party (first five parties shown below)

colours_fra_parties <- c(
  "PCF"   = "#E4002B",
  "DVG"   = "#FFC0C0",
  "FI"    = "#C9462C",
  "FI (E)"= "#C9462C",
  "PS"    = "#ED1651") # ... and so on for every single party

I fed the shapefile and colours into ggplot like this

df %>% 
  ggplot() +
  geom_sf(
    aes(fill = party_2017),
    colour = "#000000", # Colour the border around each electorate
    lwd = 0.1           # Specify width of the border lines 
    ) + 
  coord_sf(                 # Centre the map on metropolitan France
    xlim = c(-5, 10),       # Degrees longitude west (-) and east (+) of GMT to map
    ylim = c(41.5, 51.5)) + # Degrees latitude south (-) and north (+) of the equator
  scale_colour_manual(  # Feed geom_sf the correct colours of each party
    values = colours_fra_parties) 

But the results produced the incorrect party colours

What am I doing wrong that geom_sf isn't recognising the hexadecimal colours that I'm feeding it?

Upvotes: 0

Views: 299

Answers (1)

Justin Singh-M.
Justin Singh-M.

Reputation: 498

Use scale_fill_manual() instead of scale_colour_manual().

https://ggplot2.tidyverse.org/reference/scale_manual.html

Upvotes: 3

Related Questions