library(tidyverse)
ggplot(mpg)+
  geom_point(aes(x=displ,y=cty,color=drv))+
  geom_line(aes(x=displ,y=cty,color=drv))

以下是结果

enter image description here

现在,我希望图例中的点和线具有不同的 colored颜色 .具体来说,例如,对于DRV为4的分类,点 colored颜色 为红色,线 colored颜色 为绿色,并且要求在图例中显示

Please avoid using 'fill' aesthetics to fill the points and 'color' aesthetics to draw the lines,因为我会对点的形状有要求.

推荐答案

Use package ggnewscale, function new_scale_colour to replace the existing, active scale with another one. See also this SO post and this R-bloggers post .
Two notes:

  • 线条宽度较大,以使点更明显;
  • 我已经更改了线和点层的顺序,以便线不会叠加点.
library(tidyverse)
library(ggnewscale)

clr_lines <- setNames(c("green", "cyan", "magenta"), c("4", "f", "r"))
clr_points <- setNames(c("red", "black", "yellow"), c("4", "f", "r"))

ggplot(mpg) +
  geom_line(aes(x = displ, y = cty, color = drv), linewidth = 3) +
  scale_color_manual(values = clr_lines) +
  # start a new scale
  new_scale_colour() +
  geom_point(aes(x = displ, y = cty, color = drv)) +
  scale_color_manual(values = clr_points)

创建于2023-12-21,共reprex v2.0.2

R相关问答推荐

R中的枢轴/转置

跨列应用多个摘要函数:summerise_all:列表对象无法强制为double类型'

如何删除多个.CSV文件的行

名称输出pmap on tible

根据多个条件增加y轴高度以适应geom_text标签

错误:非常长的R行中出现意外符号

如何编辑gMarginal背景以匹配绘图背景?

无法定义沿边轨迹的 colored颜色 渐变(与值无关)

如何基于两个条件从一列中提取行

方法::slotName如何处理非类、非字符的参数?

用R ggplot2求上、下三角形中两个变量的矩阵热图

QY数据的处理:如何定义QY因素的水平

R -如何分配夜间GPS数据(即跨越午夜的数据)相同的开始日期?

将数据集旋转到长格式,用于遵循特定名称模式的所有变量对

如何使用FormC使简单算术运算得到的数字是正确的?

R仅当存在列时才发生变异

整理ggmosaic图的标签

如何在R中创建这些列?

Ggplot2:添加更多特定 colored颜色 的线条

如何从矩阵绘制环弦图