簡體   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