R语言 使用ggplot2将图例打印到面积图

rt4zxlrg  于 2023-06-27  发布在  其他
关注(0)|答案(1)|浏览(89)

我试图在我的面积图中添加图例,但我遇到了问题,我无法将它们定位到图表的右侧,这是我的代码,这是我的数据data

library(ggplot2)

df <- read.csv("/home/pronostico_gas.csv")
gas <- as.data.frame(df[, 1:3])

ggplot(gas) +
  geom_area(aes(x = año, y = qg),
            colour = "#E2E418", fill = "#E2E418", alpha = 0.7, show.legend = TRUE) +
  geom_line(aes(x = año, y = np),
            colour = "#C5B21D", size=1, linetype = "dashed", show.legend = TRUE) +
  scale_x_continuous(breaks = gas$año) +
  scale_y_continuous(breaks = seq(0, 250, 40)) +
  labs(title = "Title", x = "año", y = "qo") +
  theme_classic() + 
  theme(plot.title = element_text(hjust = 0.5))

yquaqz18

yquaqz181#

在缺乏可重复数据的情况下,这可能是一个帮助。在调用aes时,将您希望显示在图例中的外观放置在scale_?_manual中,并使用scale_?_manual控制外观。

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.3

gas <- data.frame(año = 2019:2042,
                  qg = runif(24, 0, 9))

gas$np = cumsum(gas$qg)

ggplot(gas) +
  geom_area(aes(x = año, y = qg, fill = "qg"),
            colour = "#E2E418", alpha = 0.7) +
  geom_line(aes(x = año, y = np, colour = "np"),
            linewidth=1, linetype = "dashed")+
  scale_colour_manual(values = "#C5B21D")+
  scale_fill_manual(values = "#E2E418")+
  guides(colour = guide_legend(override.aes = list(fill = "white"))) +
  scale_x_continuous(breaks = gas$año) +
  scale_y_continuous(breaks = seq(0, 250, 40)) +
  labs(title = "Title", 
       x = "año", 
       y = "qo",
       colour = "Colour",
       fill = "Fill") +
  theme_classic() + 
  theme(plot.title = element_text(hjust = 0.5),
        axis.text.x = element_text(size = 6),
        legend.position = "right")

创建于2023-06-21使用reprex v2.0.2

相关问题