1

在下面的代码中,我p1使用来自df1. 我想在 中的score每个项目的值处添加一条水平线df2,并使用列中包含的每个项目的相应十六进制代码为每一行着色item_hexcode

我认为将十六进制代码传递给 ggplot 以确定每行的颜色会很简单,但我似乎无法弄清楚如何去做。我尝试的每种方法要么引发错误,要么似乎将十六进制代码视为一个因素的字符串/级别。

谁能指出我哪里出错了?

library(tidyverse)
# create example dataframes
set.seed(123)
df1 <- tibble(x = 1:5, y = (sample(200:300, 5, replace = TRUE)/100))
df2 <- tibble(item = c("a", "a", "b", "c", "b"), 
              score = c(2.58, 2.63, 2.45, 2.13, 2.29), 
              item_hexcode = c("#DA020E", "#DA020E", "#034694", "#7CFC00", "#034694"))

# initial plot
p1 <- ggplot(df1, aes(x, y)) + geom_line() + ylim(2, 3)
p1

# overlay horizontal lines on first plot, and colour lines according to hexcodes
p2 <- p1 + geom_hline(data = df2, aes(yintercept = score, 
             colour = item_hexcode), linetype = "dashed" ) + 
  scale_color_manual(values = df2$item_hexcode)

p2

示例图

谢谢!

4

2 回答 2

8

我认为您正在寻找名为的函数scale_color_identity

p2 <- p1 + geom_hline(data = df2, aes(yintercept = score, 
                                      colour = item_hexcode), 
                      linetype = "dashed" ) + 
  scale_color_identity()

p2

结果

当您为美学参数设置的变量所取的值可以直接使用时使用此功能(这里的值是可以直接解释ggplot为颜色的十六进制代码)。

scale_color_manual如果您的变量中有级别(例如“低”、“中”、“高”),并且想要为它们分配特定颜色(而不是默认颜色或调色板中的颜色),您会使用这些级别。

于 2020-03-09T14:57:33.903 回答
4

您也可以I()直接在调用中使用有点未知的功能。

# overlay horizontal lines on first plot, and colour lines according to hexcodes
p1 + geom_hline(data = df2, 
                aes(yintercept = score, colour = I(item_hexcode)), 
                linetype = "dashed" 
    )

在此处输入图像描述

于 2020-03-09T15:28:48.653 回答