ggplot2设置特定颜色的单个类别

时间:2019-09-29 04:59:02

标签: r ggplot2

我有一个数据框,其中包含2个类别,每个类别在时间序列(每天的日期点击)上具有“真”或“假”点击计数

   time                groupClick clickedTrue count
   <dttm>              <chr>      <fct>       <int>
 1 2016-06-02 00:00:00 A 0        0              57
 2 2016-06-02 00:00:00 A 1        1               1
 3 2016-06-02 00:00:00 B 0        0              50
 4 2016-06-02 00:00:00 B 1        1               5
 5 2016-06-03 00:00:00 A 0        0              64
 6 2016-06-03 00:00:00 A 1        1               2
 7 2016-06-03 00:00:00 B 0        0              68
 8 2016-06-03 00:00:00 B 1        1               4
 9 2016-06-04 00:00:00 A 0        0              53
10 2016-06-04 00:00:00 A 1        1               2

我想为每个类别分配特定的颜色。例如:

  • 如果类别组单击=“ A 0”将颜色设置为RED //“#FF0000”
  • 如果类别组单击=“ A 1”将颜色设置为绿色//“#00FF00”
  • 如果类别groupClick =“ B 0”将颜色设置为蓝色//“#0000FF”
  • 如果类别groupClick =“ B 1”将颜色设置为Navi蓝色//“#00FFFF”?

如何为geom_point指定它?

到目前为止,我的代码:

ggplot(ABTestDFSum, aes(x = time, y = count)) + 
  geom_point(aes(col=groupClick, size=count)) 
  # What do we add here 

1 个答案:

答案 0 :(得分:0)

以下是根据您的帖子评论中的建议使用scale_color_manual的示例。

library(dplyr)
library(ggplot2)

df <- tribble(~time, ~groupClick, ~clickedTrue, ~count,
"2016-06-02 00:00:00", "A 0",        0,              57,
"2016-06-02 00:00:00", "A 1",        1,               1,
"2016-06-02 00:00:00", "B 0",        0,              50,
"2016-06-02 00:00:00", "B 1",        1,               5,
"2016-06-03 00:00:00", "A 0",        0,              64,
"2016-06-03 00:00:00", "A 1",        1,               2,
"2016-06-03 00:00:00", "B 0",        0,              68,
"2016-06-03 00:00:00", "B 1",        1,               4,
"2016-06-04 00:00:00", "A 0",        0,              53,
"2016-06-04 00:00:00", "A 1",        1,               2) %>%
  mutate(time = as.Date(time),
         groupClick = as.factor(groupClick),
         clickedTrue = as.logical(clickedTrue))

ggplot(df, aes(x = time, y = count)) + 
  geom_point(aes(color = groupClick, size=count)) +
  scale_color_manual(values = c("#FF0000", "#00FF00", "#0000FF", "#00FFFF"))

enter image description here