Raul
Raul

Reputation: 139

R Its possible to invert the colours palette with ggplot?

I have plotted a map with the cumulative incidence for my country. Spain. But I want to invert the color palette, because I prefer the dark colours in the worst places. But I don´t know how to do it.

The shapefiles are here: shapefiles I have uploaded the .xml data here: xml data this is my code:

     library(readxl)
library(tidyverse)
library(stringr)
library(ggplot2)

# para manipular dataframes
library(tidyverse)

# para importar archivos shapefiles
library(rgdal)

# Para transformar los archivos shapefiles 
library(broom)



setwd("C:/Users/.............../ComunidadesAutonomas_ETRS89_30N")



# Guardamos el archivo shapefile
shapefile_ccaa <- readOGR("Comunidades_Autonomas_ETRS89_30N.shp")



# Para convertir el archivo shapefile en un dataframe utilizamos la función tidy()
data_ccaa <- tidy(shapefile_ccaa)

#Creamos el dataframe para extraer los nombres de la variable Texto
nombres_ccaa <- data.frame(shapefile_ccaa$Texto)
#Asociamos las id con sus respectivos nombres de ccaa
nombres_ccaa$id <- as.character(seq(0, nrow(nombres_ccaa)-1))

#CREAMOS UN nuevo Dataframe juntando los dos anteriores por la id
data_ccaa_mapa <- left_join(data_ccaa, nombres_ccaa, by = "id")


scale_fill_brewer(
  type = "seq",
  palette = "Blues",
  direction = -1,
)



incidencia2 <- read_excel("incidencia.xls")





head(incidencia2, n=20)


incidencia2$id <- as.character(incidencia2$id)

incidencia_grafico2 <- data_ccaa_mapa %>%
  left_join(incidencia2, by= "id")

head(incidencia_grafico2)



incidencia_grafico2 %>%
  ggplot(aes(x=long, y= lat, group = group)) +
  geom_polygon(aes(fill=Incidencia_acumulada), color= "black", size = 0.2) +
  #scale_color_manual(values = RColorBrewer::brewer.pal(3,'Blues')) 
  scale_color_manual(values = rev(RColorBrewer::brewer.pal(3,'Blues')))

Can you help me with the colours? i want to invert the colours

Upvotes: 2

Views: 1742

Answers (1)

Julian_Hn
Julian_Hn

Reputation: 2141

Updated Answer after more information

So the problem was that your values were continuous not discrete, which breaks the first solution. Here is a solution that does what you want:

## Choose the colors for the color gradient. In this case I used the colors you tried to use, but can be chosen freely

cols <- RColorBrewer::brewer.pal(3,'Blues')[c(1,3)]

incidencia_grafico2 <- data_ccaa_mapa %>%
  left_join(incidencia2, by= "id")

incidencia_grafico2 %>%
  ggplot(aes(x=long, y= lat, group = group)) +
  geom_polygon(aes(fill=Incidencia_acumulada), color= "black", size = 0.2) +
  scale_fill_gradient(low=cols[1],high=cols[2]) #use a color gradient for continuous values

enter image description here

Old Answer

Just replace the

scale_color_manual(values = RColorBrewer::brewer.pal(3,'Blues'))

statements with

scale_fill_brewer(
  type = "seq",
  palette = "blues",
  direction = -1,
)

to reverse the color palettes.

Upvotes: 3

Related Questions