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

标签 r ggplot2

继续我之前的question ,我面临着问题。来订购图例。最初发布的问题具有序数(有序)值,因此工作得很好。图例中呈现的数据实时按字母顺序排序。


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")


我尝试了以下方法,但输出没有任何区别。

  1. df$variable <- factor(df$variable, levels = c("Survey", "WhatIf", "Projected1", "Projected2" ))

  2. scale_fill_discrete(breaks = c("Survey", "WhatIf", "Projected1", "Projected2" ))

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

最佳答案

您只需向 scale_color_manual 添加一个 breaks = 参数,并更改 values = 的顺序以进行匹配,因为您有 Guide 参数设置为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/

相关文章:

r - 在ggplot中绘制具有不同日期的时间线的问题

r - 如何使用GGPLOT Facet创建4x4散点图

mysql - 将 R 连接到远程 MySQL 服务器 - 无法连接到服务器

r - 在 R 中通过 git2r::clone 使用 SSH 身份验证时获取 `unsupported URL protocol`

r - X轴日期不按时间顺序排列

r - 为每个方面添加带有人口中位数的 hline

r - 将自定义标签添加到 ggplot geom_contour

r - R中的多元分解?

r - R-从存储在变量中的函数名称调用函数吗?

R. 尝试将元素分配给该对象时未找到对象错误