如何在R的ggplot2圖表中建立不同顏色的水平線?


為了在R的ggplot2圖表中建立不同顏色的水平線,我們可以按照以下步驟操作:

  • 首先,建立一個數據框。
  • 然後,使用ggplot2和geom_hline函式建立一個帶有水平線的圖表。
  • 之後,使用col引數定義線條顏色來建立相同的圖表。

建立資料框

讓我們建立一個如下所示的資料框:

 線上演示

x<-sample(1:100,20)
y<-sample(1:1000,20)
df<-data.frame(x,y)
df

執行上述指令碼後,將生成以下輸出(由於隨機化,此輸出在您的系統上可能會有所不同):

    x  y
1  85  35
2  91  593
3  19  491
4  40  601
5  84  283
6  18  179
7  88  349
8  47  769
9  30  279
10 62  881
11 3   930
12 94  429
13 77  576
14 52  792
15 37  757
16 89  405
17 73  713
18 23 72
19 96 931
20 92 350

使用ggplot2建立圖表

使用ggplot2函式建立x和y之間的散點圖,並在600處新增水平線:

x<-sample(1:100,20)
y<-sample(1:1000,20)
df<-data.frame(x,y)
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()+geom_hline(yintercept=600)

輸出

建立帶有彩色水平線的圖表

在geom_hline中使用col引數建立彩色水平線:

x<-sample(1:100,20)
y<-sample(1:1000,20)
df<-data.frame(x,y)
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()+geom_hline(yintercept=600,col=2)

輸出

更新於:2021年8月14日

881 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告