【问题标题】:Change colours of ggplot2 (R) using column names使用列名更改 ggplot2 (R) 的颜色
【发布时间】:2017-04-04 22:32:19
【问题描述】:

我有一个数据框(见下文),我想更改 ggplot2 中绘图的颜色,以便所有 A 的颜色为红色,B 的颜色为蓝色,C 的颜色为黑色,D 的颜色为黄色。

myDF

label    A    B    C    D
lab1 0.69 0.65 0.73 0.71
lab2 0.43 0.41 0.47 0.41
lab3 0.53 0.47 0.57 0.53
lab4 0.55 0.47 0.60 0.55
lab5 0.53 0.47 0.58 0.53

我尝试了以下方法:

p <- ggplot(myDF, aes(x=label)) 
     + geom_point(aes(y=A))
     + geom_point(aes(y=B))
     + geom_point(aes(y=C))
     + geom_point(aes(y=D))
     + scale_colour_manual(values=c("A"="red", "B"= "blue", "C"="black", "D"="yellow"))

但它给了我一个错误。如果我不添加 scale_colour_manual 部分,它会给出正确的图,但都是黑点。我怎样才能做到这一点?提前致谢!

【问题讨论】:

  • 将数据从“宽”重新排列为“长”;即将列名 A、B 等设为新列。有很多工具可以做到这一点,从重塑到 tidyr 等。
  • +s 放在行尾而不是开头,或者(可能取决于您的运行方式)您会收到错误,因为后续行不会包含在调用中.此外,在此处将您的数据重新整形为长格式是一个更好的主意,因此您只需在此处调用一个geom_point。要使用现有的,您只需在每个 geom_point 调用中指定颜色即可。
  • @alistaire 实际上,我在 geom_point 的 aes 中使用了 colour= 并且没有用。但无论如何,从宽到长是要走的路。
  • 您可以按原样执行,即ggplot(myDF, aes(x = label)) + geom_point(aes(y = A, color = 'A')) + geom_point(aes(y = B, color = 'B')) + geom_point(aes(y = C, color = 'C')) + geom_point(aes(y = D, color = 'D')) + scale_colour_manual(NULL, values = c(A = "red", B = "blue", C = "black", D = "yellow")),但长格式最终会更有用。

标签: r plot ggplot2


【解决方案1】:

首先将您的数据转换为长格式。我会重新考虑白底黄字。

library(tidyr)
library(ggplot2)

myDF %>% 
  gather(key, value, -label) %>% 
  ggplot(aes(label, value)) + geom_point(aes(color = key)) +
    scale_colour_manual(values=c("red", "blue", "black", "yellow"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-10
    • 2021-08-21
    • 2018-09-13
    • 2018-09-21
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多