具有多个变量的 ggplot 的图例

Legends to ggplot with multiple variables

我有一个来自模拟的多个变量的 gg 路径图,我正在尝试添加图例。我尝试了以前帖子中的多种方法,但均未成功。使用下面的代码,我只获得以下 Graph 。如果有帮助,图例名称应与变量名称相同。

ggplot(Optimisation,aes(x=Iteration,y=get("Window width")))+geom_path(color="orange",size=0.3)+
  geom_path(aes(y=get("Horizontal offset")),color="blue",size=0.3)+
  geom_path(aes(y=get("Vertical offset")),color="green",size=0.3)+
  geom_path(aes(y=get("Window height")),color="purple",size=0.3)+
  ylim(0,5)+
  labs(x="UDI [-]",y="Energy need [kWh/m²]")+
  theme(axis.title = element_text(size=8),axis.text = element_text(size=7))+
  scale_color_manual(name = "Parameter",values = c( "Window width" = "orange", 
 "Horizontal offset" = "blue", "Vertical offset" = "green","Window height"="purple"), 
  labels = c("Window width", "Vertical offset", "Horizontal offset","Window width"))

有人对此有解决方案吗?


没有数据很难重现您的问题。有关提示,请参阅 How to As and here。 无论如何,问题似乎出在您的数据结构上。 Ggplot 最适用于“tidy”数据。这个基于 mtcars 的例子可能会给出一个想法:

    library(tidyverse)

    ## create an example data set - mgp, cyl and disp are the variables I'd like to plot with coloured lines:
    plot_df <- tibble(car_name = rownames(mtcars), mpg = mtcars$mpg, cyl = mtcars$cyl, disp = mtcars$disp)
        
    ## re-shape / "tidy" the data - I'm using pivot_longer from tidyverse:
    plot_df <- plot_df %>% pivot_longer(cols = c(mpg, cyl, disp))

    ## and plot:
    ggplot(plot_df, aes(x = car_name, y = value, colour = name, group = name)) + 
        geom_line() +
        theme(axis.text.x = element_text(angle = 90))