簡體   English   中英

R:ggplot2中geom中點和線的順序

[英]R: Order of points and lines within geom in ggplot2

我正在嘗試在ggplot中繪制一個數據框,但在獲取點和線以所需順序顯示時遇到了麻煩。

數據是基於同一列(因數0或1)划分的,我希望0在線和點(使用來自其他4個單獨列的數據)上繪制1。

我在下面做了一個測試數據框來說明我的觀點。 我的真實數據框具有數千個點,並且我想繪制多個數據框,所以實際上並不想使用像對我的數據進行子集並將其繪制為單獨的圖層/幾何體這樣的變通方法。

testdata <- data.frame(Split = c(rep(0,5), rep(1,5)), a = rep(1:5,2), 
      b = c(7,8,9,10,11,6,8,9,10,12), x = c(1:5, 1:5), y = c(1:3,5,6,1.1,2.1,4.1,5.1,7.1))
testdata$Split <- factor(testdata$Split)


ggplot(data = testdata)+
  geom_point(aes(x = x, y = y, colour = Split), size = 4)+
  geom_line(aes(x = a, y = b, colour = Split))

testdata$Split <- ordered(testdata$Split, levels = rev(levels(testdata$Split)))

當我運行代碼行以反轉我的級別的順序時,它將交換我的哪一行顯示在最前面,而不交換哪一組點。 因此,最初與Split = 0相關的點和線都在后面,但是當我顛倒順序時,從Split = 0開始的線在前面(我想要的),但是Split = 0的點仍在Split = 1的點后面。

任何想法在這里發生什么以及我如何使它工作都將不勝感激。

謝謝

在調查了一段時間后,這就是我發現並提出的建議。 簡而言之,我相信解決方案是在unclass()中將值2賦給0。

foo <- data.frame(split = rep(c("0", "1"), each = 5),
             a = rep(1:5,2), 
             b = c(7,8,9,10,11,6,8,9,10,12),
             x = c(1:5, 1:5),
             y = c(1:3,5,6,1.1,2.1,4.1,5.1,7.1),
             stringsAsFactors=F)

為了將unclass() 2分配給split中的0,我做了以下工作。

foo <- arrange(foo, desc(split))
foo$split <- as.factor(foo$split)

#> str(foo)
#'data.frame':  10 obs. of  5 variables:
# $ split: Factor w/ 2 levels "0","1": 2 2 2 2 2 1 1 1 1 1
# $ a    : int  1 2 3 4 5 1 2 3 4 5
# $ b    : num  6 8 9 10 12 7 8 9 10 11
# $ x    : int  1 2 3 4 5 1 2 3 4 5
# $ y    : num  1.1 2.1 4.1 5.1 7.1 1 2 3 5 6

再一次,0在unclass()有2個。

#> unclass(foo$split)
# [1] 2 2 2 2 2 1 1 1 1 1
#attr(,"levels")
#[1] "0" "1"

現在,我運行以下命令。 q(分數)具有理想的結果。 但是q2(對於行)則不然。

q <- ggplot(data = foo, aes(x = x, y = y, colour = split))+
     geom_point(size = 6)

q2 <- ggplot(data = foo, aes(x = a, y = b, colour = split))+
      geom_line()

因此,我顛倒了因子順序,看看會發生什么。

### Reorder the factor levels.      
foo$split <- ordered(foo$split, rev(levels(foo$split)))

#> str(foo)
#'data.frame':  10 obs. of  5 variables:
#$ split: Ord.factor w/ 2 levels "1"<"0": 1 1 1 1 1 2 2 2 2 2
#$ a    : int  1 2 3 4 5 1 2 3 4 5
#$ b    : num  6 8 9 10 12 7 8 9 10 11
#$ x    : int  1 2 3 4 5 1 2 3 4 5
#$ y    : num  1.1 2.1 4.1 5.1 7.1 1 2 3 5 6

#> unclass(foo$split)
#[1] 1 1 1 1 1 2 2 2 2 2
#attr(,"levels")
#[1] "1" "0"

第3季度和第4季度均獲得正確的結果。

q3 <- ggplot(data = foo, aes(x = x, y = y, colour = split))+
      geom_point(size = 6)

q4 <- ggplot(data = foo, aes(x = a, y = b, colour = split))+
      geom_line()

所以,這是最終形式。

ggplot(data = foo)+
  geom_point(aes(x = x, y = y, colour = split), size = 6)+
  geom_line(aes(x = a, y = b, colour = split))

在此處輸入圖片說明

暫無
暫無

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

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