簡體   English   中英

使用geom_line()在ggplot2中進行線型映射

[英]linetype mapping in ggplot2 using geom_line()

我有一個看起來像這樣的數據集:

   case prop weight  res
1     A   10    0.1 0.81
2     A   20    0.2 0.78
3     A   30    0.3 0.76
4     A   40    0.4 0.58
5     A   50    0.1 0.62
6     A   10    0.2 0.73
7     A   20    0.3 0.68
8     A   30    0.4 0.70
9     A   40    0.1 0.55
10    A   50    0.2 0.78
11    A   10    0.3 0.64
12    A   20    0.4 0.68
13    A   30    0.1 0.75
14    A   40    0.2 0.67
15    A   50    0.3 0.59
16    A   10    0.4 0.77
17    A   20    0.1 0.57
18    A   30    0.2 0.61
19    A   40    0.3 0.60
20    A   50    0.4 0.72
21    B   10    0.1 0.66
22    B   20    0.2 0.66
23    B   30    0.3 0.76
24    B   40    0.4 0.57
25    B   50    0.1 0.83
26    B   10    0.2 0.68
27    B   20    0.3 0.76
28    B   30    0.4 0.65
29    B   40    0.1 0.70
30    B   50    0.2 0.72
31    B   10    0.3 0.60
32    B   20    0.4 0.82
33    B   30    0.1 0.85
34    B   40    0.2 0.72
35    B   50    0.3 0.74
36    B   10    0.4 0.67
37    B   20    0.1 0.60
38    B   30    0.2 0.62
39    B   40    0.3 0.76
40    B   50    0.4 0.87
41    C   10    0.1 0.48
42    C   20    0.2 0.77
43    C   30    0.3 0.70
44    C   40    0.4 0.65
45    C   50    0.1 0.73
46    C   10    0.2 0.70
47    C   20    0.3 0.80
48    C   30    0.4 0.68
49    C   40    0.1 0.58
50    C   50    0.2 0.63
51    C   10    0.3 0.71
52    C   20    0.4 0.68
53    C   30    0.1 0.84
54    C   40    0.2 0.66
55    C   50    0.3 0.77
56    C   10    0.4 0.67
57    C   20    0.1 0.64
58    C   30    0.2 0.74
59    C   40    0.3 0.81
60    C   50    0.4 0.62

數據可以通過以下代碼生成:

 case = rep(c("A", "B", "C"), each=20)
    prop = rep(c("10", "20", "30", "40", "50"), 12)
    weight = as.factor(rep(c(0.1, 0.2, 0.3, 0.4), 15))
    res = round(rnorm(n=60, 0.7, 0.1), 2)

    dat = data.frame(case, prop, weight, res)
    dat

我要實現的是將“ prop”作為x軸,將“ res”作為y軸,同時使用不同的顏色區分“大小寫”,並使用不同的線型區分“權重”。 例如,如果weight = 0.1,則使用實線;否則,使用實線。 如果weight = 0.2,則使用虛線等。從下面的代碼中:

ggplot(data = dat, aes(x=prop, y=res, group=case, color=case)) +
  geom_line() +
  geom_point() + 
  theme_bw()

我只能得到以下不需要的圖... 在此處輸入圖片說明

我嘗試添加geom_line(aes(linetype=weight)) ,但顯示錯誤

Error: geom_path: If you are using dotted or dashed lines, colour, size and linetype must be constant over the line

有沒有辦法將“權重”映射到ggplot2中的線型? 謝謝!

您可以創建一個新變量來分組並用於指定線型。

dat$case.weight <- paste0(dat$case, dat$weight)

..並添加scale_linetype_manual()

ggplot(data = dat, aes(x=prop, y=res, group=case.weight, color=case, linetype=case.weight)) +
  scale_linetype_manual(values=rep(c("solid", "dashed", "dotted", "dotdash"),3), 
                        breaks=c("A0.1","A0.2", "A0.3", "A0.4"),
                        labels=c("0.1", "0.2", "0.3", "0.4"),
                        name="weight") +
  geom_line() +
  geom_point() + 
  theme_bw()

在此處輸入圖片說明

暫無
暫無

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

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