首页 > 解决方案 > 具有多个变量的 ggplot 图例

问题描述

我有一个模拟中多个变量的 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"))

有人对此有解决方案吗?


标签: rggplot2legend

解决方案


没有数据就很难重现您的问题。有关一些提示,请参阅How to As此处。无论如何,问题似乎在于您的数据结构。Ggplot 最适合“整洁”的数据。这个基于 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))

推荐阅读