如何在带有条形图和点的图中显示图例?

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

我有一个数据框,如下所示:

  COUNTRY YEAR   y
     AT 2019    25
     AT 2020    38.0
     AT 2021    23.4
     BE 2019    11.1
     BE 2020    18.6
     BE 2021    15.0
     DK 2019    31.1
     DK 2020    43.6
     DK 2021    42.0

我使用条形图(年份 = 2021)和点(年份 = 2015、2019)来绘制它。我在让图例正确显示正确的符号方面遇到一些问题。我确实得到了下图

这是我正在使用的代码的最终版本:

countries <- c("AT", "BE", "DK")
years <- c(2019, 2020, 2021)
values <- c(25, 38.0, 23.4, 11.1, 18.6, 15.0, 31.1, 43.6, 42.0)

df <- data.frame(
  COUNTRY  = rep(countries, each = 3),
  YEAR = rep(years, times = 3),
  y = values
)
ggplot(df, aes(x = COUNTRY, y = y, group = YEAR, shape = as.factor(YEAR))) +
      geom_bar(data = subset(df, YEAR == 2021), aes(fill = "2021"), stat = 'identity', position = 'dodge', alpha = 0.7) +
      geom_point(data = subset(df, YEAR == 2020), aes(fill = "2020"), position = position_dodge(width = 0.4), size = 3, shape = 19, color = "red") +
      geom_point(data = subset(df, YEAR == 2019), aes(fill = "2019"), position = position_dodge(width = 0.4), size = 3, shape = 4, color = "blue") +
      scale_fill_manual(values = c("2021" = "grey", "2020" = "red", "2019" = "blue")) +
      labs(x = "Country", y = "y", fill = "") +
      theme_minimal() +
      theme(legend.position = "right")

我希望图例仅显示 YEAR = 2021 年的“条形”/填充框,以及分别显示 2020 年和 2019 年的两种不同形状。

r ggplot2 legend geom-bar geom-point
1个回答
1
投票

这是实现您想要的结果的一种选择,它正确地映射到美学,而不是在

geom_point
中将颜色和形状设置为参数,并注意所有三个图例(
fill
color
shape
)合并。最后,我使用
override.aes
guide_legend
参数来删除图例中点的填充颜色。

library(ggplot2)

ggplot(df, aes(x = COUNTRY, y = y, group = YEAR, shape = factor(YEAR))) +
  geom_col(
    data = subset(df, YEAR == 2021), aes(fill = factor(YEAR)),
    position = "dodge", alpha = 0.7
  ) +
  geom_point(
    data = subset(df, YEAR %in% 2019:2020),
    aes(color = factor(YEAR)),
    position = position_dodge(width = 0.4), size = 3
  ) +
  scale_fill_manual(
    values = c("2021" = "grey", "2020" = "red", "2019" = "blue"),
    aesthetics = c("color", "fill")
  ) +
  scale_shape_manual(
    values = c("2020" = 19, "2019" = 4, "2021" = NA),
  ) +
  labs(x = "Country", y = "y", fill = NULL, color = NULL, shape = NULL) +
  theme_minimal() +
  theme(legend.position = "right") +
  guides(
    fill = guide_legend(override.aes = list(fill = c(NA, NA, "grey")))
  )

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