我有一個資料框架df,有4個唯一的UID - 1001,1002,1003,1004。
我想在R中寫一個用戶定義的函式,做以下事情:
- 為每個獨特的
UID繪制Turbidity與Time的對比圖。 濁度值是Time_1、Time_2和Time_3列中的數值。例如,UID = 1001將在一個圖中有4個圖 。
為每個圖形添加一個圖例,如
M-L、F-L、M-R和F-R(從列Gen和Type)給每個圖形添加一個標題。例如-
UID:1001將圖表匯出為pdf或jpeg或tiff pdf檔案--每頁4個圖表
# dataset
Gen < - c('M'。 'M','M'。 'M','F'。 'F','F','F'。 'M','M'。 'M','M'。 'F','F'。 'F','F')
網站 < - rep('FRX'。 length(gen))
輸入< - c('L'。 'L','L'。 'L','L'。 'L','L','L'。 'R','R'。 'R','R'。 'R','R'。 'R','R')
UID < - c(1001。 1002, 1003。 1004, 1001, 1002,1003, 1004。 1001, 1002。 1003, 1004。 1001, 1002。 1003,1004)
時間_1 <- c(100. 78,112.34,108. 52,139.19,149. 02,177.77,79.18, 89. 10,106.78,102. 34,128.52,119. 19,129.02,147. 77,169.18,170.11)
時間_2 <- c(150.78,162. 34,188.53,197. 69,208.07,217. 76,229.48,139. 51,146.87,182. 54,189.57,199. 97,229.28,247. 73,269.91,249.19)
時間_3 <- c(250.78,262. 34,288.53,297. 69,308.07,317. 7,329.81,339. 15,346.87,382. 54,369.59,399. 97,329.28,347. 73,369.91,349.19)
df <- data. frame(Gen,Site,Type, UID,Time_1,Time_2, Time_3)
df
我的嘗試
library(ggplot2)
library(tidyr)
# See below for my thoughts/attempt- I am open to other R libraries and approaches
graphplotter <-function(x){>
# 1. 從寬轉換為長
data_long < - gather(df, time, turbidity, Time_1: Time_3, factor_key=TRUE)
延長線
#2.為每個獨特的UID-1001至1004繪圖并添加圖例。
基本 < - ggplot(datalong, aes(time,濁度, shape=Tree) geom_point() geom_line()
基本 主題()
legend.position = c(. 95, .95),
圖例。 理由= c("right"。 "top"),
legend.box.just = "right",。
圖例。 margin = margin(6,/span> 6。 6, 6))
#3.添加標題。
print(basic labs( title= "UID。1001, Tubidity against time", y="濁度"。 x = "Time in hours"))
#4.匯出為pdf。
pdf("turbdity-time.pdf"/span>)
par(mfrow = c( 2, 2)) ##設定布局為2乘2
sapply(1: 4。 function(i) plot(basic[, i]))
dev.off()
}
我希望所有的四個圖表看起來都像這樣(忽略周長和年齡,應該是濁度和時間)。
謝謝
uj5u.com熱心網友回復:
我使用facet_wrap
graphplotter < -function(x){
x%>%
gather(. ,時間,濁度,Time_1。 Time_3, factor_key=TRUE) %>;%
mutate(label = (paste0(Gen。 "-"。 型別)) %> %
#group_by(UID) %>%
ggplot(aes(color = label)) geom_point(aes(time, 濁度,形狀= 標簽。 組= label))
geom_line(aes(時間,濁度。 組= label)) facet_wrap(~UID) 主題()
圖例。 position = c(1。 1),
圖例。 justification = c("right"。 "top"),
legend.box.just = "right",。
圖例。 margin = margin(1,/span> 1, 1, 1),
圖例。 text = element_text(size = 7))
}。
graphplotter(DF)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/317215.html
標籤:
下一篇:C#方法通過字串動態地制作表格



