r - R - ggplot 自定义图例
问题描述
我在 R 中的 ggplot 中创建了图形,除了图例之外,我实际上对此非常满意,我只想在其中包含颜色和线型变化的图例。
我的代码是:
x <- data.frame(
"type" = c("new", "new", "old", "old", "new", "new", "old", "old"),
"date" = as.Date(c("2018-01-01", "2018-01-01", "2018-01-01", "2018-01-01", "2018-01-08", "2018-01-08", "2018-01-08", "2018-01-08")),
"score" = c("1.5", "2.5", "2.6", "3.7", "5.2", "8.6", "5.2", "8.6"),
"category" = c("actual", "predicted", "actual", "predicted", "actual", "predicted", "actual", "predicted"),
stringsAsFactors = F)
library(ggplot2)
ggplot(x, aes(x=date, y=score, group = paste(category, type), linetype = category, colour = paste(category, type))) +
geom_line(size = 1.25) +
scale_color_manual(
values = c("#4286f4", "#f9026d", "#4286f4", "#f9026d")
)
结果应该是
解决方案
我相信以下内容可以满足问题的要求。它的灵感来自这个问题的答案。诀窍是使labels
和 的比例与和name
相等。为了使代码更简单,
我已经编辑了这些列并开始了。scale_color_manual
scale_linetype_manual
paste
category
type
library(ggplot2)
colr <- paste(x$category, x$type)
ggplot(x, aes(x = date, y = score,
group = colr,
linetype = colr,
colour = colr)) +
geom_line(size = 1.25) +
scale_color_manual(
values = c("#4286f4", "#f9026d", "#4286f4", "#f9026d"),
labels = sort(unique(colr)),
name = "category and type"
) +
scale_linetype_manual(values = c(1, 1, 3, 3),
labels = sort(unique(colr)),
name = "category and type")
推荐阅读
- vue.js - Vue 无法读取未定义的属性
- laravel - Laravel 5.3 日志权限 - 以无人身份创建/写入:nogroup
- android - 意图失败并在 SpeechFactory.fromSubscription 上取消(LUIS azure,android sdk)
- xgboost - Python、XGBoost、自定义目标函数:预测在迭代过程中保持不变,即使梯度不为零
- python - 将 Flask 请求注入另一个 Flask 应用程序
- r - H0 和 FM 指数下的贝克伽马分布 (dendextend)
- javascript - 实现泛型类型的打字稿泛型类
- vba - 根据单元格值复制数据
- javascript - Jimdo:使用 javascript/jquery 将占位符添加到 html
- linux - 使用 YYYYMMDD_HHMMSS.csv.gz 格式在 shell 中获取最新文件