[英]multiple lines plot using multiple groups in data
根據某些條件,我想繪制如下數據:
WC ASL TS LPD
7101 3 L 573.57
7101 3 L 323.33
7102 4 R 113.36
7102 4 R 3.05
7103 7 L 204.72
7103 7 L 123.65
7104 21 R 252.36
7104 21 R 225.74
7104 21 R 147.79
7104 21 R 151.47
7105 27 L 350.51
7105 27 L 41.61
7105 27 L 22.29
7105 27 L 2.00
繪圖條件為:
我正在嘗試這樣的事情:
ggplot(df2, aes(LPD, ASL, TS, colour=WC)) +
geom_line() +
geom_point()
混亂不堪...可能是您可以幫助我更好地了解情節。
因為上述內容可能會使許多人困惑,所以我將使其變得更簡單:
grp LPD
1 0.56744
1 0.4200938
2 0.070033616
2 0.065484951
3 0.327293
3 0.4718639
3 0.539516903
3 0.672646939
3 0.769603286
3 0.560730825
3 0.592725708
4 0.27415791
4 0.17706706
4 0.084262982
4 0.220420565
5 1.066580889
5 0.663611983
5 0.005299676
5 0.180121466
5 0.055205502
6 0.435355273
6 0.544843791
7 2.437439375
7 0.631948813
7 0.165961834
7 0.092725372
7 0.262442283
9 0.268541902
9 0.041798885
11 0.348282689
11 0.033044253
11 0.046070074
11 0.127173837
11 0.030580852
12 7.213290722
12 2.738036844
12 1.581291713
12 1.234204974
12 0.043930992
12 0.089781343
12 0.077482862
12 0.056506104
12 0.007676594
OP尚不完全清楚所需的輸出是什么。 但是,從注釋中得出結論可能是這樣的:
要創建該圖,需要將數據從寬格式重整為長格式。 ggplot2
首選長格式。 為此,使用了data.table
包中的melt()
。
library(data.table)
df2 <- fread(
"WC ASL TS LPD
7101 3 L 573.57
7101 3 L 323.33
7102 4 R 113.36
7102 4 R 3.05
7103 7 L 204.72
7103 7 L 123.65
7104 21 R 252.36
7104 21 R 225.74
7104 21 R 147.79
7104 21 R 151.47
7105 27 L 350.51
7105 27 L 41.61
7105 27 L 22.29
7105 27 L 2.00"
)
# reshape from wide to long format
molten <- melt(setDT(df2), id = "LPD")
# ensure that factor levels are in order of appearance
molten[, value := forcats::fct_inorder(value)]
str(molten)
#Classes ‘data.table’ and 'data.frame': 42 obs. of 3 variables:
# $ LPD : num 573.57 323.33 113.36 3.05 204.72 ...
# $ variable: Factor w/ 3 levels "WC","ASL","TS": 1 1 1 1 1 1 1 1 1 1 ...
# $ value : Factor w/ 12 levels "7101","7102",..: 1 1 2 2 3 3 4 4 4 4 ...
# - attr(*, ".internal.selfref")=<externalptr>
請注意, melt()
在一個value
列中收集(或收集)了WC
, ASL
和TS
列的所有值,此后為類character
。
繪制時, ggplot2
隱式地將字符轉換為因數,從而對級別使用字母排序順序。 這意味着ASL
的值以ASL
的順序繪制,而不是3、4、7、21、27的順序繪制。
為了使值的順序保持在數據中,通過使用forcats
包中方便的fct_inorder()
函數可以明確地強制forcats
。
library(ggplot2)
ggplot(molten, aes(x = value, y = LPD)) +
geom_line() +
geom_point() +
facet_wrap(~ variable, scales = "free_x") +
theme_bw()
OP已提供了其他數據。 這些可以使用geom_step()
與
ggplot(DT2, aes(x = grp, y = LPD)) + geom_point() + geom_step() +
theme_bw()
請注意,x軸將grp
顯示為連續刻度。
根據評論 ,OP希望將行作為“階梯線” 。 不幸的是,OP尚未指定確切沿x軸顯示的內容。 因此,這是OP可能會看到的另一種瘋狂猜測:
DT2[, grp := factor(grp)]
ggplot(DT2, aes(x = seq_len(nrow(DT2)), y = LPD, group = grp, colour = grp)) +
geom_point() + geom_step() +
theme_bw()
請注意,此處的數據點是連續編號的。 這些數字顯示在x軸上。 數據點通過步進功能逐組連接。 此外,這些組還用顏色編碼。
如果數據點在每個組中編號,則每個組都以1開頭,則結果將顯示得更加緊湊。
DT2[, rn := factor(rowid(grp))]
ggplot(DT2, aes(x = rn, y = LPD, group = grp, colour = grp)) +
geom_point() + geom_step() +
theme_bw()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.