mon*_*nis 1 r colors ggplot2 geom-hline
在下面的代码中,我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
Run Code Online (Sandbox Code Playgroud)
谢谢!
我认为您正在寻找名为的函数scale_color_identity:
p2 <- p1 + geom_hline(data = df2, aes(yintercept = score,
colour = item_hexcode),
linetype = "dashed" ) +
scale_color_identity()
p2
Run Code Online (Sandbox Code Playgroud)
当您为美学参数设置的变量所取的值可以直接使用时使用此函数(这里的值是可以直接解释ggplot为颜色的十六进制代码)。
你可以使用scale_color_manual,如果你在你的变量(如“低”,“中等”,“高”)有水平,并希望指定特定的颜色来(而不是默认的,或者颜色调色板)。
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"
)
Run Code Online (Sandbox Code Playgroud)