I’m trying to exert more control on the legends for a plot (ggplot2) with two y-axes

I would like the top legend to not have the points. That legend is for the stacked barplot (percentage of total funding) and should just show the category color.

I would like the bottom legend to show the line + colored shape of the line plots (number of projects).

data

library(tidyverse)
library(openxlsx)
library(ggplot2)
library(cowplot)

# Load the data
new_data = read.xlsx("processed_2008-2020.xlsx")

max_projects <- max(new_data$number_of_projects, na.rm = TRUE)

# Create the main plot (without legends)
main_plot <- new_data %>%
  ggplot(aes(x = year)) +
  geom_bar(
    aes(y = pct_total_funding * 100, fill = category),
    stat = "identity",
    position = "stack",
    alpha = 0.6
  ) +
  geom_line(
    aes(y = number_of_projects * (100 / max_projects), group = category),
    color = "black",
    linewidth = 0.7,
    alpha = 0.7
  ) +
  geom_point(
    aes(y = number_of_projects * (100 / max_projects), shape = category, fill = category),
    color = "black",  # Black outline for shapes
    size = 3,
    stroke = 0.5,
    alpha = 0.7
  ) +
  scale_shape_manual(values = c(21, 22, 23, 24)) +
  scale_fill_brewer(palette = "Dark2") +
  scale_x_continuous(
    name = "Funding Year",
    breaks = unique(new_data$year),
    labels = function(x) str_glue("{x}")
  ) +
  scale_y_continuous(
    name = "Percentage of Total Funding",
    breaks = seq(0, 100, by = 20),
    minor_breaks = seq(0, 100, by = 10),
    labels = percent_format(scale = 1),
    sec.axis = sec_axis(~ . * (max_projects / 100),
                        name = "Number of Projects",
                        labels = scales::comma_format()),
    limits = c(0, NA),
    expand = expansion(mult = c(0, 0.05))
  ) +
  labs(
    title = "US Autism Research Funding by Category",
    subtitle = "Federal and Private",
    fill = "Percentage of Total Funding",
    shape = "Number of Projects"
  ) +
  theme_light() +
  theme(
    plot.title = element_text(hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5),
    legend.position = "bottom",
    legend.box = "vertical",  # Stacked one above the other
    legend.title = element_text(size = 12),
    legend.text = element_text(size = 11),
    axis.text.x = element_text(angle = 45, hjust = 1),
    panel.grid.major.x = element_blank(),
    panel.grid.minor.x = element_blank(),
    panel.border = element_blank(),
    axis.ticks.y = element_blank()
  )

# Adjust the top legend to remove points (only showing fill colors for the bar plot)
main_plot <- main_plot + 
  guides(
    fill = guide_legend(title = "Percentage of Total Funding"),
  )

# Print the final plot with refined legends
print(main_plot)

Recognized by R Language Collective

2

An easy option to achieve your desired result would be to user the ggnewscale package which allows for multiple scales for the same aesthetic, i.e. the fill aes in your case.

library(tidyverse)
library(scales, warn = FALSE)
library(ggnewscale)

# Load the data
new_data <- read_csv(
  "https://gist.githubusercontent.com/abalter/14c9135f295419d6590f79b2b9b10c5c/raw/2493dfc087a34f091052a6586c608fb1be86ce1c/iacc_processed_2008-2020.csv",
  show_col_types = FALSE
)

max_projects <- max(new_data$number_of_projects, na.rm = TRUE)

# Create the main plot (without legends)
new_data %>%
  ggplot(aes(x = year)) +
  geom_bar(
    aes(y = pct_total_funding * 100, fill = category),
    stat = "identity",
    position = "stack",
    alpha = 0.6
  ) +
  scale_fill_brewer(palette = "Dark2", name = "Percentage of Total Funding") +
  ggnewscale::new_scale_fill() +
  geom_line(
    aes(y = number_of_projects * (100 / max_projects), group = category),
    color = "black",
    linewidth = 0.7,
    alpha = 0.7
  ) +
  geom_point(
    aes(y = number_of_projects * (100 / max_projects), shape = category, fill = category),
    color = "black", # Black outline for shapes
    size = 3,
    stroke = 0.5,
    alpha = 0.7
  ) +
  scale_shape_manual(values = c(21, 22, 23, 24)) +
  scale_fill_brewer(palette = "Dark2", name = "Number of Projects") +
  scale_x_continuous(
    name = "Funding Year",
    breaks = unique(new_data$year),
    labels = function(x) str_glue("{x}")
  ) +
  scale_y_continuous(
    name = "Percentage of Total Funding",
    breaks = seq(0, 100, by = 20),
    minor_breaks = seq(0, 100, by = 10),
    labels = percent_format(scale = 1),
    sec.axis = sec_axis(~ . * (max_projects / 100),
      name = "Number of Projects",
      labels = scales::comma_format()
    ),
    limits = c(0, NA),
    expand = expansion(mult = c(0, 0.05))
  ) +
  labs(
    title = "US Autism Research Funding by Category",
    subtitle = "Federal and Private",
    shape = "Number of Projects"
  ) +
  theme_light() +
  theme(
    plot.title = element_text(hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5),
    legend.position = "bottom",
    legend.box = "vertical", # Stacked one above the other
    legend.title = element_text(size = 12),
    legend.text = element_text(size = 11),
    axis.text.x = element_text(angle = 45, hjust = 1),
    panel.grid.major.x = element_blank(),
    panel.grid.minor.x = element_blank(),
    panel.border = element_blank(),
    axis.ticks.y = element_blank()
  )

Recognized by R Language Collective

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật