r - 具有多个变量的 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"))
有人对此有解决方案吗?
解决方案
没有数据就很难重现您的问题。有关一些提示,请参阅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))
推荐阅读
- r - 在 R data.table 中按组绘制点
- shopify - Shopify 液体,在液体文件中获取客户的 billing_address
- typescript - Typescript 可测试的函数式编程
- javascript - 当父容器元素具有溢出滚动时,这是否可以使子 dom 元素具有可见的溢出?
- c# - 使用样式设置按钮内容时的 WPF 奇怪行为
- java - 如何使用多个java文件,每个文件夹中的每个文件?
- sql - 灵活的结果表,列基于另一个表的行
- asp.net - 如何使页面接受 asp.net 中的 mimetype
- java - DTO、DAO 和实体?需要实体吗?这3个的最佳实践?
- java - Java - 使用三个线程处理文件