How to create cowplot panel with side and top headings and a common legend?

56 views Asked by At

I want to create a choropleth panel with side and top headings and a common legend. I am plotting a choropleth over the state of Texas for four different scenarios. I want to show it as a 2x2 panel. I am using the plot_grid method from the R cowplot library to generate the panel.

Here's what I want it to look like, enter image description here

Here's a snippet of the code that I have till now,

CPC_grids_deviations <- merge(CPC_grids, tx_deviation_df)

create_grids_deviation_map <- function(data) {
  grids_deviation_map <- tm_shape(texas) +
    tm_borders() +
    tm_shape(CPC_grids_deviations) +
    # Setting fixed style so that all maps have a consistent, comparable scale
    tm_fill(col = data, palette = "Blues",  style = "fixed", breaks = c(0, 1, 21, 41, 61, 81, 101, 121, 140),
            legend.show = FALSE) +
    tm_borders(col = "grey60", lwd = 0.5) +
    tm_layout(frame = FALSE)

  return(tmap_grob(grids_deviation_map))
}


plot_grid(
  create_grids_deviation_map("total_cpc_90"), create_grids_deviation_map("total_chirps_90"),
  create_grids_deviation_map("total_cpc_70"), create_grids_deviation_map("total_chirps_70"),
  ncol = 2
)

And here's the output so far,
enter image description here

I am able to generate just the legend using the following code,

create_legend <- function(data) {
  legend <- tm_shape(texas) +
    tm_borders() +
    tm_shape(CPC_grids_deviations) +
    tm_fill(col = data, palette = "Blues", title = "Count", style = "fixed", breaks = c(0, 1, 21, 41, 61, 81, 101, 121, 140)) +
    tm_layout(legend.only = TRUE)

  return(legend)
}
create_legend("total_cpc_90")

But I am not sure how to include the generated legend in the panel as shown in the expected output.

1

There are 1 answers

0
qh_tan On

Try patchwork::plot_layout(guides = 'collect'). See https://patchwork.data-imaginist.com/articles/guides/layout.html

p1 <- create_grids_deviation_map("total_cpc_90")
p2 <- create_grids_deviation_map("total_chirps_90")
p3 <- create_grids_deviation_map("total_cpc_70")
p4 <- create_grids_deviation_map("total_chirps_70")


p1 + p2 + p3 + p4 +
  plot_layout(guides = 'collect')

To add the side and top headings, use patchwork::plot_annotation(). See https://patchwork.data-imaginist.com/articles/guides/annotation.html