gpt4 book ai didi

r - ggplot2 |如何自定义图例中字符串值的顺序?

转载 作者:行者123 更新时间:2023-12-04 09:30:53 25 4
gpt4 key购买 nike

延续我之前的 question ,我面临着问题 w.r.t.订购传奇。最初发布的问题具有序数(有序)值,因此效果很好。图例中呈现的数据实时按字母顺序排列。

library(ggplot2)
library(tidyverse)
library(reshape2)

#Creating a dataframe with use-case specific variables.
df = data.frame(
Year = 2006:2025,

Survey = c(40.5, 39.0, NA, NA, NA, NA, 29.9, NA, NA, NA, 21.6,
NA, NA, NA, NA, NA, NA, NA, NA, NA),

Projected1 = c(NA, NA, NA, NA, NA, NA, 29.9, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, 14.9),

WhatIf= c(NA, NA, NA, NA, NA, NA, 29.9, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, 13.0),

Projected2 = c(NA, NA, NA, NA, NA, NA, 29.9, 27.6, 25.4, 23.4, 21.6,
19.9, 18.4, 16.9, 15.6, 14.4, 13.3, NA, 12.2, 11.3)
)

#Transforming data
df <- melt(df,id.vars = "Year")

ggplot(data = NULL, aes(x=factor(Year), y=value, group=variable)) +
geom_line(data = df[!is.na(df$value) & df$variable != "Survey",],
aes(linetype=variable, color = variable), size = 1, linetype = "dashed")+
geom_point(data = df[!is.na(df$value) & df$variable == "Survey",],
aes(color = variable), size = 4) +
scale_color_manual(values=c('#999999', 'orange2','turquoise2','blue2'))+
guides(color = guide_legend(override.aes = list(linetype = c("blank", "dashed", "dashed", "dashed"),
shape = c(16, NA, NA, NA)))) +
scale_y_continuous(
breaks=seq(0,100, 10), labels = seq(0, 100, 10), limits=c(0,70),
sec.axis = dup_axis()) +
theme(
legend.position = 'bottom', legend.direction = 'horizontal',
panel.grid.major.y = element_line(color='gray85'),
axis.title = element_text(face='bold')) +

labs(x='Year', y='measure (%)')

Created on 2020-07-11 by the reprex package (v0.3.0)

输出
enter image description here
目标:图例和相应图中的序列必须如下: c("Survey", "WhatIf", "Projected1", "Projected2")

我也尝试了以下方法,但输出没有区别。
  • df$variable <- factor(df$variable, levels = c("Survey", "WhatIf", "Projected1", "Projected2" ))
  • scale_fill_discrete(breaks = c("Survey", "WhatIf", "Projected1", "Projected2" ))

  • 我可能会错过一个微不足道的步骤,任何建议都会非常有帮助。

    最佳答案

    你只需要添加一个 breaks =论据 scale_color_manual并更改 values = 的顺序匹配,因为您将指南参数设置为 color = :

    scale_color_manual(breaks = c("Survey", "WhatIf", "Projected1", "Projected2" ),
    values=c('turquoise2','blue2','#999999', 'orange2'))+
    enter image description here

    关于r - ggplot2 |如何自定义图例中字符串值的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62852018/

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