gpt4 book ai didi

r - 如何重新排序 ggplot2 中具有scale_colour_manual 和scale_linetype_manual 的图例?

转载 作者:行者123 更新时间:2023-12-02 02:48:49 25 4
gpt4 key购买 nike

我需要更改 ggplot 图例中的顺序。下面复制了用于此目的的简单图。如何让“Forecaster_2”出现在“Forecaster_1”之前?我尝试过休息,但无法使其发挥作用。

library(ggplot2)

x_1 <- rep(0:6, each = 2)
pdf_1 <- c(0,0.05,0.05,0.1,0.1,0.15,0.15,0.3,0.3,0.25,0.25,0.15,0.15,0)

x_2 <- rep(3:9, each = 2)
pdf_2 <- c(0,0.05,0.05,0.1,0.1,0.15,0.15,0.3,0.3,0.25,0.25,0.15,0.15,0)

data_1 <- data.frame(x_1, pdf_1,x_2,pdf_2)

ggplot()+
geom_line(data=data_1,aes(x=x_1, y=pdf_1, color="Forecaster_1", linetype='Forecaster_1'),size=1)+
geom_line(data=data_1,aes(x=x_2, y=pdf_2, color="Forecaster_2", linetype='Forecaster_2'),size=1)+
labs(x = "x") +
labs(y = "PDF") +
scale_colour_manual("Line", values = c('Forecaster_1' = 'cornflowerblue', 'Forecaster_2' = 'coral2')) +
scale_linetype_manual("Line", values = c('Forecaster_1' = 'solid', 'Forecaster_2' = 'dashed'))+
theme(legend.position="top",
legend.title=element_blank())

最佳答案

编辑:

library(tidyverse)
df<-data_1 %>%
pivot_longer(everything(),
names_to = c(".value", "group"),
names_sep = "_"
) %>%
mutate(
group = factor(group, levels = c(2,1),
labels = c('Forecater_2', 'Forcaster_1')))

df %>%
ggplot(aes(x= x, y = pdf, color=group, linetype = group))+
geom_line() +
theme(legend.position="top",
legend.title=element_blank())

enter image description here

关于r - 如何重新排序 ggplot2 中具有scale_colour_manual 和scale_linetype_manual 的图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62399686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com