我正在努力使用創建直方圖矩陣lapply()。以下生成九個直方圖,但 x 標簽是資料第一行中的值,而不是列名。我希望 x 標簽是列的名稱。
library(tidyverse)
library(ISLR2)
library(gridExtra)
data(College)
plothists<-function(colm) {
ggplot(College) geom_histogram(aes(colm),binwidth=20) xlab(label=colm)
}
plist<-lapply(College[,c(2:10)],plothists)
grid.arrange(grobs=as.list(plist),ncol=3)
如何將列名作為 x 標簽?
編輯:我接受 JPSmith 的回答,但我出于自己的目的修改了代碼,如下所示:
library(tidyverse)
library(ISLR2)
data(College)
College |>
pivot_longer(2:10,names_to="var") |>
ggplot(aes(value)) geom_histogram(bins=60)
facet_wrap(~var,scales="free")
theme(axis.text.x=element_text(angle=45,hjust=1))
uj5u.com熱心網友回復:
您可以通過簡單地將資料轉換為長格式并使用 ggplot 來使用當前的庫來實作這一點:
# transform to long
newdata <- College %>%
pivot_longer(2:10, names_to = "hist")
ggplot(newdata)
geom_histogram(aes(value), binwidth = 20)
facet_wrap(~hist, ncol = 3, scales = "free")
輸出:

uj5u.com熱心網友回復:
我找到了一種更簡單的方法來做到這一點
library(tidyverse)
library(ISLR2)
data(College)
library(reshape2)
cmelt<-melt(College[,c(2:10)])
ggplot(cmelt,aes(value)) geom_histogram(bins=60)
facet_wrap(~variable,scales="free")
theme(axis.text.x=element_text(angle=45,hjust=1))
在另一個堆疊溢位問題中!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/482753.html
