繁体   English   中英

使用R中的ggplot2渐变时颜色为0

[英]Wrong color for 0 in gradient using ggplot2 in R

我正在尝试绘制ggplot2图,将点和线段的颜色映射到连续变量(在这种情况下为时间)。 这些点会根据渐变和映射到该颜色的时间显示我期望的颜色,但是当time = 0时,第一个点的线段则不会。 这是一个例子:

Oxy <- data.frame(Time = c(0, 0.5, 1, 1.5, 2, 4, 8, 12),
              DrugConc = c(0, 8, 12, 13, 10, 7.5, 5, 2.5),
              Pupil = c(0, -0.04, -0.1, -0.25, -0.23, -0.2, -0.15, -0.08))

for(j in 1:(nrow(Oxy)-1)){
      Oxy$Xstart[j] <- Oxy$Pupil[j]
      Oxy$Xend[j] <- Oxy$Pupil[j+1]
      Oxy$Ystart[j] <- Oxy$DrugConc[j]
      Oxy$Yend[j] <- Oxy$DrugConc[j+1]
}

ggplot(Oxy, aes(x = Pupil, y = DrugConc, color = Time)) +
      geom_point() +
      geom_segment(data = Oxy,
                   aes(x = Xstart, xend = Xend, y = Ystart, yend = Yend),
                   arrow = arrow(length = unit(8, "points"), type = "open")) +
      xlab("Percent change in pupil diameter") + 
      ylab("Oxycodone concentration (ng/mL)")

结果如下图所示: 在此处输入图片说明

就像第一点一样,第一段应该是深蓝色,而不是浅蓝色。 我想念什么吗?

Oxy的第八行基本上覆盖了第一行。 我通过将“ Time更改为一个因子并添加size作为一种美感来形象化这一点,以便我们可以轻松地查看ggplot()功能。

library(ggplot2)
Oxy <- data.frame(Time = c(0, 0.5, 1, 1.5, 2, 4, 8, 12),
                  DrugConc = c(0, 8, 12, 13, 10, 7.5, 5, 2.5),
                  Pupil = c(0, -0.04, -0.1, -0.25, -0.23, -0.2, -0.15, -0.08))

for(j in 1:(nrow(Oxy)-1)){
  Oxy$Xstart[j] <- Oxy$Pupil[j]
  Oxy$Xend[j] <- Oxy$Pupil[j+1]
  Oxy$Ystart[j] <- Oxy$DrugConc[j]
  Oxy$Yend[j] <- Oxy$DrugConc[j+1]
}
#Plot just the first four row segments
ggplot(Oxy[1:4,], aes(x = Pupil, y = DrugConc, colour = factor(Time), size = factor(Time))) +
  geom_point() +
  geom_segment(aes(x = Xstart, xend = Xend, y = Ystart, yend = Yend),
               arrow = arrow(length = unit(8, "points"), type = "open")) +
  scale_colour_brewer(type = "div")
#> Warning: Using size for a discrete variable is not advised.

#plot rows 5 - 8
ggplot(Oxy[5:8,], aes(x = Pupil, y = DrugConc, colour = factor(Time), size = factor(Time))) +
  geom_point() +
  geom_segment(aes(x = Xstart, xend = Xend, y = Ystart, yend = Yend),
               arrow = arrow(length = unit(8, "points"), type = "open")) +
  scale_colour_brewer(type = "div")
#> Warning: Using size for a discrete variable is not advised.

reprex软件包 (v0.2.1)创建于2019-01-15

简而言之-输入数据中可能存在错误, ggplot()正在执行应做的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM