带连接点的散点图中数据点的条件格式

时间:2017-03-24 17:58:09

标签: r ggplot2 line scatter-plot conditional-formatting

根据以下数据框和图,我想在did.it=="y"时有条件地将数据点的颜色更改为黑色。然而,点的形状和线的颜色应保持不变。我怎么能这样做?

set.seed(4887)
Strain <- rep(c(rep("A", times = 2), rep("B", times = 4)), times = 2)
Sex_ID <- rep(c("M_1", "F_2", "M_3", "F_4", "M_5", "F_6"), times = 2)
State <- rep(c("virgin", "mated", "expecting", "parent"), each = 6)
Huddling <- runif(8, 1.5, 3.8)
did.it<-rep(c("y","n","n"), times=8)

d <- data.frame(Strain, Sex_ID, State, Huddling, did.it)

library(tidyr)
d <- d %>% 
  separate(Sex_ID, c('Sex', 'ID'), sep = '_')

ggplot(d, aes(x = factor(State), y = Huddling, color = Sex, group = ID, shape = ID))+
  facet_grid(Strain ~ ., scales = 'free_y') +
  geom_point(size = 3, position = position_dodge(width=0.3), show.legend = F) + 
  geom_line(size = 0.7, position = position_dodge(width=0.3)) +
  scale_color_manual(values = c('red4', 'midnightblue')) +
  scale_fill_manual(values = "white") +
  scale_x_discrete(limits = c("virgin", "mated", "expecting", "parent"), 
                   labels = c("Virgin", "Mated", "Expecting", "Parent")) +
  labs(y = "Time huddling (s)", x = "Reproductive stage") +
  theme_classic() +
  theme(axis.line.x = element_line(color = "black", size = 1),
        axis.line.y = element_line(color = "black", size = 1),
        axis.text = element_text(size = 17),
        axis.title = element_text(size = 19,face = "bold"),
        legend.title = element_text(size = 17),
        legend.text = element_text(size = 15),
        plot.title = element_text(lineheight = .8, face = "bold",size = 22))

Here is the plot at the moment

1 个答案:

答案 0 :(得分:0)

你可以通过以下方式实现目标:

 geom_point(size = 3, aes(color = did.it) ...) + 
...
  scale_color_manual(values = c('red4', 'midnightblue', 'orange', 'black')) ...

但是这并没有留下积分&#39; did.itFALSE时颜色不变。所以:

d$point_col <- ifelse(d$did.it=='y', 'y', d$Sex)

ggplot(d, aes(x = factor(State), y = Huddling, color = Sex, group = ID, shape = ID))+
  facet_grid(Strain ~ ., scales = 'free_y') +
  geom_point(size = 3, aes(color = point_col), position = position_dodge(width=0.3), 
        show.legend = F) + 
  geom_line(size = 0.7, position = position_dodge(width=0.3)) +
  scale_color_manual(values = c('red4', 'midnightblue',  'black')) +
  scale_fill_manual(values = "white") +
  scale_x_discrete(limits = c("virgin", "mated", "expecting", "parent"), 
    labels = c("Virgin", "Mated", "Expecting", "Parent")) +
  labs(y = "Time huddling (s)", x = "Reproductive stage")

(加上你额外的主题陈述。)