简体   繁体   中英

Wrong color for 0 in gradient using ggplot2 in R

I'm trying to make a ggplot2 plot with the colors of points and segments mapped to a continuous variable (time, in this case). The points show up with colors I'd expect based on the gradient and the time mapped to that color, but the segment for the first point, when time = 0, does not. Here's an example:

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)")

This results in this graph: 在此处输入图片说明

The first segment should be dark blue, not light blue, just like the first point. Am I missing something?

The 8th row of Oxy basically overplots the first row. I visualized this by changing Time to a factor and also adding size as an aesthetic so we can easily see what ggplot() is doing.

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.

Created on 2019-01-15 by the reprex package (v0.2.1)

In short - there's likely a bug in your input data, ggplot() is doing what it's supposed to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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