如何在R中使用ggplot2添加图例而不使用aes()?

vlju58qv  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(119)

我目前正在使用条形图和折线图绘制一个双轴图,并想在图表底部添加一个图例,以显示蓝色条形图代表新建筑,橙子线表示平均租金价格。然而,我无法在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()

字符串

hc2pp10m

hc2pp10m1#

您可以在color和/或fill aes上Map一个常量值,然后通过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")

字符串

相关问题