问题描述
我需要在一个图中绘制数据帧所有列的ECDF,并在轴上也获得x_limit。
我写的函数:
library(lattice)
library(latticeExtra)
ecdf_plot <- function(data){
# Drop columns with only NA's
data <- data[,colSums(is.na(data)) != nrow(data)]
data$P_key <- NULL
ecdfplot(~ S12,data=data,auto.key=list(space='right'))
}
问题: 上面函数中的ECDF仅针对S12列进行绘制,但对于数据框中的所有列我都需要此图。我知道我可以执行S12 + S13 + ...,但是源数据发生了变化,我们不完全知道数据帧将获得多少列和哪些列。有没有更好的办法吗?另外,是否有可能使组合图的x_limit仅为xlim(0,100)之类的一个范围?
解决方法
我认为使用ggplot可以更轻松地完成此任务。根据需要设置限制,自定义外观等非常容易。
函数如下所示:
state | wait_event | wait_event_type | count
--------+---------------------+-----------------+-------
| AutoVacuumMain | Activity | 1
| BgWriterHibernate | Activity | 1
| CheckpointerMain | Activity | 1
idle | ClientRead | Client | 525
| LogicalLauncherMain | Activity | 1
| WalWriterMain | Activity | 1
active | | | 1
现在让我们在随机数据帧上对其进行测试:
library(dplyr)
library(tidyr)
library(ggplot2)
ecdf_plot <- function(data) {
data[,colSums(is.na(data)) != nrow(data)] %>%
pivot_longer(everything()) %>%
group_by(name) %>%
arrange(value,by_group = TRUE) %>%
mutate(ecdf = seq(1/n(),1 - 1/n(),length.out = n())) %>%
ggplot(aes(x = value,y = ecdf,colour = name)) +
xlim(0,100) +
geom_step() +
theme_bw()
}