首页 > 解决方案 > 有没有办法在同一个 ggplot 上使用 2 个色标?

问题描述

将数据按类别(样本 A 和 B)分开,制作了 2 层,一层用于点,一层用于线。我想按类别分隔我的数据,指示点的颜色,并分隔线,但颜色与用于点的颜色不同。

library(ggplot2)

Sample <- c("a", "b")
Time <- c(0,1,2)

df <- expand.grid(Time=Time, Sample = Sample)
df$Value <- c(1,2,3,2,4,6)

ggplot(data = df,
             aes(x = Time,
                 y = Value)) +
  geom_point(aes(color = Sample)) +
  geom_line(aes(color = Sample)) +
  scale_color_manual(values = c("red", "blue")) + #for poits
  scale_color_manual(values = c("orange", "purple")) #for lines

标签: rggplot2colorsgeom

解决方案


使用ggnewscale包可以这样实现:

library(ggplot2)
library(ggnewscale)
Sample <- c("a", "b")
Time <- c(0,1,2)

df <- expand.grid(Time=Time, Sample = Sample)
df$Value <- c(1,2,3,2,4,6)

ggplot(data = df,
       aes(x = Time,
           y = Value)) +
  geom_point(aes(color = Sample)) +
  scale_color_manual(name = "points", values = c("red", "blue")) + #for poits
  new_scale_color() +
  geom_line(aes(color = Sample)) +
  scale_color_manual(name = "lines", values = c("orange", "purple")) #for lines


推荐阅读