r - ggplot 报告连续变量是分类的;我错过了什么?
问题描述
我正在尝试遍历数据框,并根据列是因子还是数字返回多面 ggplot。
library(tidyverse)
d <- mtcars
# make a couple factors
d2 <- d %>% mutate_at((vars(matches("cyl"),matches("gear"))), as.factor)
#check
(d2 %>% map_lgl(is.factor))
(d2 %>% map_lgl(is.numeric))
这有效:
plot_chart <- function(df, na.rm = TRUE){
nm = names(df)
for (i in nm) {
nm_p <- grep(paste("^",i,"$",sep=""), nm) #finds the position of i in the sequence
g <- ggplot(df, aes_string(x = i))
print(nm_p) # progress to console
if (is.factor(df[,nm_p])==TRUE) {
g <- g + geom_bar()
} else if (is.numeric(df[,nm_p])) {
g <- g + geom_histogram(bins = 10)
}
g <- g + facet_wrap(~cyl,nrow=1) + labs( x = i)
print(g)
# indexes and saves
# idx <- paste(sprintf("%04d", nm_p), "_Cyl_by_", i,".svg", sep="")
# ggsave(idx , device="svg", width = 10, height = 10, units = "cm")
}
}
plot_chart(d2) #Success!
然而,尝试进一步抽象函数(最终目标是添加额外的图表类型和优化输入),失败了:
callplot <- function(df, na.rm = TRUE){
nm = names(df)
for (i in nm) {
#finds the position of i in the sequence
nm_p <- grep(paste("^",i,"$",sep=""), nm)
# print(nm_p) # progress to console
if (is.factor(df[,nm_p])==TRUE) {
t <- "fac"
} else if (is.numeric(df[,nm_p])) {
t <- "num"
}
plotme(df, i, t)
}
}
plotme <- function(df, x, type, na.rm = TRUE){
xq <- enquo(x)
g <- ggplot(df, aes(x = !! xq))
if (type=="fac") {
g <- g + geom_bar()
} else if (type=="num") {
print(x)
g <- g + geom_histogram(bins=10) #<--- fails here
}
g + facet_wrap(~cyl,nrow=1) + labs( x = x)
print(g)
}
callplot(d2)
错误是:
错误:StatBin 需要一个连续的 x 变量:x 变量是离散的。也许你想要 stat="count"?
但是,mpg
正如逻辑所决定的那样,是一个数字而不是一个因素。这与enquo
和有关!!
吗?这些对我来说代表了一个全新的混乱程度。
我错过了什么?
解决方案
推荐阅读
- javascript - Discord.js Bot 在使用命令时崩溃
- ruby-on-rails - 使用 Chartkick 和图表 js 的 Rails 双轴
- excel - 将数据从 Word 发送到 Excel:运行时错误:需要“424”对象
- javascript - 如何在 vuetify 中强制使用 v-switch?
- c++ - 获取“Hello triangle”程序来渲染三角形的问题
- java - Java Android 开发“SSL 库失败,通常是协议”
- c - 使用 netlink 从旧内核上的套接字获取 inode
- javascript - 尝试使用我自己的 webpack 配置在 .vue 文件中获取本地图像时出错
- angular - 如果在 Angular 8 中输入的数字少于 10 位,则将类添加到输入
- c++ - 在 Visual Studio 2019 中使用 Qt 时出错