簡體   English   中英

R: ggplot: two plots in one dataframe: color one plot only when it is less than the other plot

[英]R: ggplot: two plots in one dataframe: color one plot only when it is less than the other plot

我有來自 plot 上的單個 dataframe 的兩個 geom_point 圖。 我想要的是僅在 Y 軸上 plot 2 低於 plot 1 時為 label 着色。 所以如果它在上面,plot2 將是灰色/黑色,當它在下面時,它將被 dataframe 中的某一列標記

df <- setNames(data.frame(c("2022-07-29 00:00:00","2022-07-29 00:00:05",
                           "2022-07-29 00:05:00","2022-07-29 00:05:05",
                           "2022-07-29 00:10:00","2022-07-29 00:15:00",
                           "2022-07-29 00:20:00","2022-07-29 00:20:05"), 
                          c(1,2,3,4,5,6,7,8), 
                          c(0.8,2.1,2.5,4.1,5,6.1,6.9,8.1),
                          c("a","a","b","b","b","b","b","c")),
                          c("timeStamp", "value1", "value2", "text"))

所以我能想出的最接近的圖表是

ggplot(df) +
geom_point(aes(timeStamp,value1))+
geom_point(aes(timeStamp, value2, color=value2>value1)) +
scale_color_manual(name="callout", values = setNames(c('green','red'), c(T,F)))

這個 plot 幾乎正是我所需要的,但我希望第一個 plot 下方的紅線使用 label 的文本列。 如果我將上面的 setNames 更改為 c('green', text),我認為它應該可以工作,但不能也無法找出正確的前進方向。 謝謝

這是我對你想要什么的解釋。 關鍵線是

callout <- factor(ifelse(df$value2 > df$value1, NA, df$text))

如果 value2 小於 value1,它將為文本列設置顏色。

library(ggplot2)
df <-
    setNames(data.frame(
        as.POSIXct(
            c(
            "2022-07-29 00:00:00",
            "2022-07-29 00:00:05",
            "2022-07-29 00:05:00",
            "2022-07-29 00:05:05",
            "2022-07-29 00:10:00",
            "2022-07-29 00:15:00",
            "2022-07-29 00:20:00",
            "2022-07-29 00:20:05"
            )),
        c(1, 2, 3, 4, 5, 6, 7, 8),
        c(0.8, 2.1, 2.5, 4.1, 5, 6.1, 6.9, 8.1),
        c("a", "a", "b", "b", "b", "b", "b", "c")
    ),
    c("timeStamp", "value1", "value2", "text"))

# this works out the colours
callout <- factor(ifelse(df$value2 > df$value1, NA, df$text))

gg2 <- 
    ggplot(df) + 
    geom_point(aes(timeStamp,value1), col='grey50', size=3) + 
    geom_point(aes(timeStamp, value2, color = callout), size=3) 

gg2

在此處輸入圖像描述

我還添加了as.POSIXct()調用,使 x 軸更整潔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM