更改 ggplot2 地图中的图例外观

问题描述 投票:0回答:1

我正在使用此代码片段构建等值线图。 图例是一个颜色渐变的宽框。 根据my_palette中的五种颜色,我更喜欢五盒颜色。 我更改为 scale_fill_manual 但出现错误:Continuous value supplied to discrete scale

# Define the color palette
my_palette <- c("#FFEDA0", "#FEB24C", "#FD8D3C", "#FC4E2A", "#800026")

# Define the legend labels
my_labels <- c("Moins de 2%", "De 2 à 4%", "De 4 à 8%", "De 8 à 15%", "Plus de 15%")

# Define the breaks values
my_breaks <- c(0, 2, 4, 8, 15)

# Merge data and geo
gazole_map <- left_join(gazole, shapefile, by = c("insee" = "INSEE_DEP"))



my_plot <- ggplot() +
  geom_sf(data = gazole_map, aes(fill = prop, geometry = geometry)) +
  theme_void() +
  scale_fill_gradientn(colors = my_palette, labels = my_labels, breaks = my_breaks) +
  
  # Add the title and subtitle
  ggtitle("Stations en rupture de gazole en métropole") +
  labs(subtitle = paste0(Sys.Date() - 1)) +
  
  # Customize the legend and source position
  theme(
    plot.margin = unit(c(1, 1, 1, 1), "lines"), # Set bottom margin to 3 lines
    legend.position = "right",
    legend.box = "vertical",
    legend.key.width = unit(0.3, "cm"), # Set the legend box width to 2cm
    legend.key.height = unit(1, "cm"),
    legend.title = element_blank(), # Remove the legend title
    legend.title.align = 1,
    legend.text.align = 0.5,
    plot.caption = element_text(hjust = 0, size = 8, margin = margin(t = 10)) # source caption left
  ) +
  
  # Add the caption
  labs(caption = "Source : Ministère de l'Economie")
r ggplot2 maps
1个回答
0
投票

一个选项是使用例如手动装箱您的

prop
cut
.

使用一些基于

nc
shapefile 的伪随机示例数据,来自
sf
包:

# Example data
gazole_map <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
gazole_map$prop <- runif(nrow(gazole_map), 0, 20)

library(ggplot2)

gazole_map$prop_cut <- cut(gazole_map$prop, c(my_breaks, Inf))

ggplot() +
  geom_sf(data = gazole_map, aes(fill = prop_cut)) +
  theme_void() +
  scale_fill_manual(values = my_palette, labels = my_labels) +
  # Add the title and subtitle
  ggtitle("Stations en rupture de gazole en métropole") +
  labs(subtitle = paste0(Sys.Date() - 1)) +

  # Customize the legend and source position
  theme(
    plot.margin = unit(c(1, 1, 1, 1), "lines"), # Set bottom margin to 3 lines
    legend.position = "right",
    legend.box = "vertical",
    legend.key.width = unit(0.3, "cm"), # Set the legend box width to 2cm
    legend.key.height = unit(1, "cm"),
    legend.title = element_blank(), # Remove the legend title
    legend.title.align = 1,
    legend.text.align = 0.5,
    plot.caption = element_text(hjust = 0, size = 8, margin = margin(t = 10)) # source caption left
  ) +

  # Add the caption
  labs(caption = "Source : Ministère de l'Economie")

© www.soinside.com 2019 - 2024. All rights reserved.