如何在不使用 R 中的 aes() 和 ggplot2 的情况下添加图例?

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

我目前正在使用条形图和折线图绘制双轴图,并想在图表底部添加图例以显示蓝色条形图代表新建筑,橙色线表示平均租金价格。但是,我无法在 ggplot 中这样做。通常我们使用 aes(color=[variable]) 但在这种情况下我只想显示代表条形图和线条的不同图。

目前我只是想添加 aes(),有没有办法更改我的代码,以便 aes() 可以读取单个变量来给我一个图例,或者我可以简单地添加一个没有 aes() 的图例我的代码?

ggplot(new_construction, aes(year, total_new_constructions)) +
  geom_col(aes(color=total_new_constructions), color="blue", fill="blue", legend.text = "Amount of new construction") +
  geom_line(aes(y = a + average_rental_prices*b, color=total_new_constructions), color = "orange", lwd=1.5, legend.text = "Average rental price") +
  scale_y_continuous(
    name = "Total New Constructions", breaks=seq(0, 30000, by=10000),
    sec.axis = sec_axis(~ (. - a)/b, name = "Average Rental Prices", breaks=seq(0,4000, by=1000))) +
  
  scale_x_continuous("Year", seq(2000, 2018))   +
  labs(title="Total New Constructions and Average Rental Prices (2000-2018)", subtitle = "Data Source: TidyTuesday R") +
  theme(legend.position="bottom") +
  theme_minimal()

r ggplot2 double legend axis
1个回答
0
投票

您可以在

color
和/或
fill
aes 上映射常量值,然后通过
scale_color/fill_manual
设置颜色和标签。

使用一些虚假的示例数据:

library(ggplot2)

new_construction <- data.frame(
  year = 2000:2018,
  total_new_constructions = seq(0, 3e4, length.out = 19),
  average_rental_prices = 800
)

a <- 1
b <- 10

ggplot(new_construction, aes(year, total_new_constructions)) +
  geom_col(
    aes(fill = "Bar"),
    color = "blue"
  ) +
  geom_line(
    aes(
      y = a + average_rental_prices * b,
      color = "Line"
    ),
    lwd = 1.5
  ) +
  scale_color_manual(
    values = "orange",
    labels = "Average rental price"
  ) +
  scale_fill_manual(
    values = "blue",
    labels = "Amount of new construction"
  ) +
  scale_y_continuous(
    name = "Total New Constructions",
    breaks = seq(0, 30000, by = 10000),
    sec.axis = sec_axis(~ (. - a) / b,
      name = "Average Rental Prices",
      breaks = seq(0, 4000, by = 1000)
    )
  ) +
  scale_x_continuous("Year", seq(2000, 2018, 2)) +
  labs(
    title = "Total New Constructions and Average Rental Prices (2000-2018)",
    subtitle = "Data Source: TidyTuesday R",
    color = NULL, fill = NULL
  ) +
  theme_minimal() +
  theme(legend.position = "bottom")

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