ggplot2绘制流感血清型月度堆叠柱状图时遇参数缺失类警告
问题描述
尝试绘制流感血清型按月份统计的堆叠柱状图时,出现以下警告,无法正常生成图表:
Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
3: In min(diff(sort(x))) : no non-missing arguments to min; returning Inf
4: Removed 7687 rows containing non-finite values (stat_count()).
使用的R代码:
library(tidyverse) library(dplyr) library(lubridate) library(ggplot2) library(ggthemes) Sys.setenv(TZ="America/New_York") today <- Sys.Date() flu2018_file <- "2018_flu.txt" df_flu2018 <- as.data.frame(read.table(flu2018_file, sep="\t", header=TRUE, check.names=FALSE, fill=TRUE)) df_flu2018$month <- floor_date(as_date(mdy(df_flu2018$date)), unit="month") plot_1 <- ggplot(df_flu2018) + geom_histogram(stat="count", aes(x = month, fill = serotype)) plot_1
数据集头部的dput输出:
df_flu2018 <- structure(list(accession = c("MH083301", "MH083303", "MH083309", "MH083311", "MH081888", "MH081892"), length = c(1752L, 1433L, 1752L, 1433L, 1441L, 1737L), host = c("Human", "Human", "Human", "Human", "Human", "Human"), segment = c("4 (HA)", "6 (NA)", "4 (HA)", "6 (NA)", "6 (NA)", "4 (HA)"), serotype = c("H1N1", "H1N1", "H1N1", "H1N1", "H3N2", "H3N2"), country = c("USA", "USA", "USA", "USA", "USA", "USA"), region = c("N", "N", "N", "N", "N", "N"), date = c("2018/01/02", "2018/01/02", "2018/01/03", "2018/01/03", "2018/01/03", "2018/01/03" ), name = c("Influenza A virus (A/Alabama/01/2018(H1N1))", "Influenza A virus (A/Alabama/01/2018(H1N1))", "Influenza A virus (A/Alabama/02/2018(H1N1))", "Influenza A virus (A/Alabama/02/2018(H1N1))", "Influenza A virus (A/Alabama/03/2018(H3N2))", "Influenza A virus (A/Alabama/03/2018(H3N2))" ), mutations = c("", "", "", "", "", ""), age = c(NA, NA, NA, NA, NA, NA), gender = c(NA, NA, NA, NA, NA, NA), lineage = c(NA, NA, NA, NA, NA, NA), vac_strain = c(NA, NA, NA, NA, NA, NA), fulllength_plus = c("c", "c", "c", "c", "c", "c"), month = structure(c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), class = "Date")), row.names = c(NA, 6L), class = "data.frame")
问题原因
从数据集的month列全为NA可以看出,日期转换失败了。你的日期格式是年/月/日(如2018/01/02),但你用了mdy()函数——这个函数是用来解析月/日/年格式的日期,自然无法正确识别,导致生成的month列全部缺失,ggplot找不到有效数据,因此抛出警告并移除所有行。
解决方案
1. 修正日期转换函数
把mdy()替换成ymd(),对应年/月/日的格式:
df_flu2018$month <- floor_date(as_date(ymd(df_flu2018$date)), unit="month")
2. 优化绘图代码(可选)
如果要绘制堆叠柱状图,用geom_col()配合预先统计好的数据会更直观,也能避免stat_count()的潜在问题:
# 先按月份和血清型统计数量 df_counts <- df_flu2018 %>% drop_na(month) %>% # 移除日期转换失败的行 count(month, serotype) # 绘制堆叠柱状图 plot_1 <- ggplot(df_counts, aes(x = month, y = n, fill = serotype)) + geom_col(position = "stack") + labs(x = "月份", y = "样本数量", fill = "血清型") + theme_minimal() plot_1
验证转换结果
运行完日期转换后,可以用head(df_flu2018$month)检查是否生成了正确的月份日期(比如2018-01-01),确认无误后再绘图即可。
内容的提问来源于stack exchange,提问作者Sarah
相关产品推荐
相关产品推荐

