我正在嘗試為我的資料框的每一列繪制一個圖,并將列名傳遞為每個圖的標題。總共有 72 列需要自己的單獨繪圖。Facet_wrap 不是解決此問題的合適方法。
運行最上面的代碼會給我一些名字不正確的地塊。這將回傳第 i 列的第一行值。我想回傳列名。 繪制名稱的第一行值
有沒有一種方法可以自動將列名稱拉入每次迭代的標題中?
這是我的資料子集
Wisconsin_GR <- read.table(header=TRUE, text="
Species Adams Ashland Barron Bayfield Brown
Ash -.5889 4.1211 5.6036 26.8347 NA
Aspen -.5867 15.82 .4329 1.1622 NA
")
回傳第一行值為 i 列的圖的代碼。
for( i in Wisconsin_GR[2:6]){
print(
gf_point(i~Species, data = test)%>%
gf_labs(title=i,
y = "Growth to Removal Ratio",
x = "")
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
scale_y_continuous(expand = c(0,0), limit = c(-5,100)))
}
下面的代碼被更改為提取列名稱,這對呼叫名稱(Wisconsin_GR)作業正常,但在輸入代碼時回傳以下錯誤。
錯誤:x 由于精度損失無法轉換為。由以下錯誤引起stop_vctrs():!由于精度損失,無法從 轉換為 。
for( i in Wisconsin_GR[2:6]){
print(
gf_point(i~Species, data = test)%>%
gf_labs(title=names(Wisconsin_GR[i]),
y = "Growth to Removal Ratio",
x = "")
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
scale_y_continuous(expand = c(0,0), limit = c(-5,100)))
}
uj5u.com熱心網友回復:
不確定你有多少行資料,因為這段代碼速度不快,但可以作業。請注意我添加的 if 條件,這可能有問題但處理起來并不復雜。并且最好說明您的資料來自何處(它來自ggformula,但我們不需要檢查自己......)。
library(tidyverse)
library(glue)
Wisconsin_GR <- read.table(header=TRUE, text="
Species Adams Ashland Barron Bayfield Brown
Ash -.5889 4.1211 5.6036 26.8347 NA
Aspen -.5867 15.82 .4329 1.1622 NA
")
# First let us create a name cloumn
names_to_plot <- colnames(Wisconsin_GR)
# Now that we have the name, we can start our loop.
for(i.tmp in 2:6){
# Pick a a title for the plot from each colname of the data
tmp.title <- names_to_plot[i.tmp]
# Pick what to plot on the x axis and also the values for each colname.
tmp.xaxis <- Wisconsin_GR %>%
select(glue("{names_to_plot[c(1,i.tmp)]}")) %>%
pull(glue("{names_to_plot[1]}"))
tmp.values <- Wisconsin_GR %>%
select(glue("{names_to_plot[c(1,i.tmp)]}")) %>%
pull(glue("{names_to_plot[i.tmp]}"))
# Now unite the three temporary variables into one single temporary data frame
tmp.df <- data.frame(
col_title=tmp.title,
Species=tmp.xaxis,
values=tmp.values
)
# The condition is added since when NA values are to be plotted, it distrupts ggplot's behaviour.
# If you dont want to skip on plotting NA values,
# You can modify the aes(x=..) to 1:length(Species),
# and add scale_x_continuous(labels = tmp.df$Species,
# breaks = 1:length(tmp.df$Species))
if(is.na(tmp.df$values[1])){next}
# With this tmp data frame we can now plot each figure
print(
tmp.df %>% ggplot(aes(x=Species,y=values))
geom_point()
labs(title=glue("Coloumn: {tmp.df$col_title[1]}"))
ylab("Growth to Removal Ratio")
theme(axis.text.x = element_text(
angle = 90, vjust = 0.5, hjust=1))
scale_y_continuous(expand = c(0,0), limit = c(-5,100))
)
}
# Get rid of all these nasty tmp varaibles. they are no longer needed.
rm(list =ls(pattern = "tmp"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/535405.html
標籤:rfor循环列名
下一篇:比較兩個資料幀并檢索值
