ggplot2 - ggplot - 行排序,一行在另一行之上
问题描述
这是我的例子:
library(ggplot2)
forecast <- c(2,2,1,2,2,3,2,3,3,3,3)
actual <- c(2,2,1,2,2,3,2,3,2,2,1)
my_df <- data.frame(forecast = forecast, actual = actual)
my_df$seq_order <- as.factor(1:NROW(my_df))
my_df <-gather(my_df, "line_type", "value", -seq_order)
ggplot(data=my_df, aes(x=seq_order, y = value,
colour = line_type, group=line_type))+geom_line()+theme(legend.position="bottom")
我希望红线在它们重合的任何地方都位于蓝线之上。我试过scale_color_manual(values = c("forecast" = "red" ,"actual" = "blue"))
了,但没有用。
解决方案
更改因子水平顺序。不要忘记也更改组。
看到这个相关的线程,为什么我使用scales::hue()
等
library(tidyverse)
forecast <- c(2,2,1,2,2,3,2,3,3,3,3)
actual <- c(2,2,1,2,2,3,2,3,2,2,1)
my_df <- data.frame(forecast = forecast, actual = actual, seq_order = 1:11)
my_df <-gather(my_df, line_type, value, -seq_order) %>% mutate(type = factor(line_type, levels = c('forecast','actual')))
ggplot(data=my_df, aes(x=seq_order, y = value,
colour = type, group = type)) +
geom_line()+
theme(legend.position="bottom") +
scale_color_manual(values = rev(scales::hue_pal()(2)))
由reprex 包(v0.3.0)于 2020-03-24 创建
推荐阅读
- java - 有什么方法可以用 Zxing 库自定义二维码数据矩阵的样式
- java - 在 Micronaut 集成测试中使用带有 OpenID Connect 的远程服务器验证 JWKS
- python - 在 python 函数中使用相同的变量两次
- detection - 访问 SMB 共享的 Suricata 规则?
- c# - .NET Core 中的每个文件的密钥配置
- ios - 按月将日期数组分组为一个字符串
- kubernetes - 如何在文本文件中获取 Kubeaudit 输出?
- html - 将异步 onSuccess 转换为 Promise 并等待
- ldap - openshift 是否支持运行 389ds?
- c# - MQTT 未连接到代理