如何在 R 資料框之外定義點並在 ggplot2 圖表中繪製它們?
要定義 R 資料框之外的點並在 ggplot2 圖表中繪製它們,我們可以按照以下步驟操作:
- 首先,建立一個數據框
- 然後,使用 ggplot2 包的 geom_point 函式建立散點圖。
- 使用資料框內部的 data.frame 建立包含資料框外部資料點的散點圖。
建立資料框
讓我們建立一個如下所示的資料框:
x<-round(rnorm(25,1,0.005),2) y<-round(rnorm(25,5,0.25),2) df<-data.frame(x,y) df
執行上述指令碼後,將生成以下輸出(由於隨機化,此輸出將在您的系統上有所不同):
x y 1 1.01 4.94 2 1.00 5.21 3 1.00 4.56 4 1.00 5.42 5 0.99 5.22 6 1.00 4.96 7 0.99 4.64 8 1.01 5.16 9 1.00 5.12 10 1.00 5.00 11 0.99 5.04 12 1.00 4.85 13 1.00 5.09 14 1.00 5.07 15 1.01 4.93 16 1.00 4.67 17 0.99 5.18 18 1.00 5.14 19 1.00 4.79 20 1.00 4.60 21 1.01 5.05 22 1.00 4.91 23 1.00 5.06 24 1.00 4.68 25 1.00 4.76
建立散點圖
使用 ggplot2 包的 geom_point 函式在 x 和 y 之間建立散點圖:
x<-round(rnorm(25,1,0.005),2) y<-round(rnorm(25,5,0.25),2) df<-data.frame(x,y) library(ggplot2) ggplot(df,aes(x,y))+geom_point()
輸出

建立包含資料框外部資料點的散點圖
使用 data.frame 函式在 geom_point 內部建立新的資料集並繪製它們:
x<-round(rnorm(25,1,0.005),2) y<-round(rnorm(25,5,0.25),2) df<-data.frame(x,y) library(ggplot2) ggplot(df,aes(x,y))+geom_point()+geom_point(data=data.frame(x=c(0.995,1.02),y=c(4.9 ,5.2)),colour="blue")
輸出

廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP