如何基于频率表绘制男女任务时长散点图?解决ggplot报错
基于频率表制作男女任务时长-频率散点图的问题与解决方法
问题背景
我通过t1 <- table(PainF$task_duration)和t2 <- table(PainM$task_duration)生成了女性和男性的任务时长频率表,表格中上方数字为任务时长(分钟),下方为对应人数的频率。尝试用ggplot绘制散点图对比男女的任务时长与频率,运行以下代码时出现报错:
ggplot() + geom_point(data = t1, aes(x = x, y = "column2"), color = "blue", size = 3) + geom_point(data = t2, aes(x = x, y = "column2"), color = "red", size = 3) + labs(x = "X", y = "Y", title = "Female and Male task duration") + theme_minimal()
报错信息
Error in
fortify():
!datamust be a <data.frame>, or an object coercible byfortify(), or a valid
<data.frame>-like object coercible byas.data.frame().
Caused by error in.prevalidate_data_frame_like_object():
!dim(data)must return an of length 2.
Runrlang::last_trace()to see where the error occurred.
附t1和t2的dput结果
> dput(t1) structure(c(`30` = 3L, `40` = 3L, `45` = 2L, `60` = 5L, `65` = 1L, `70` = 2L, `75` = 1L, `78` = 1L, `80` = 1L, `90` = 5L, `95` = 1L, `100` = 1L, `101` = 1L, `120` = 3L, `144` = 1L, `150` = 1L, `180` = 1L, `185` = 1L, `240` = 2L), dim = 19L, dimnames = list(c("30", "40", "45", "60", "65", "70", "75", "78", "80", "90", "95", "100", "101", "120", "144", "150", "180", "185", "240")), class = "table") > dput(t2) structure(c(`2` = 2L, `10` = 2L, `15` = 1L, `20` = 2L, `30` = 3L, `38` = 1L, `40` = 4L, `45` = 4L, `50` = 3L, `55` = 2L, `60` = 11L, `70` = 1L, `72` = 1L, `73` = 1L, `75` = 1L, `80` = 2L, `90` = 10L, `95` = 1L, `100` = 1L, `105` = 1L, `110` = 1L, `120` = 11L, `130` = 2L, `150` = 2L, `180` = 5L, `200` = 1L, `240` = 3L, `300` = 3L, `500` = 1L ), dim = 29L, dimnames = structure(list(c("2", "10", "15", "20", "30", "38", "40", "45", "50", "55", "60", "70", "72", "73", "75", "80", "90", "95", "100", "105", "110", "120", "130", "150", "180", "200", "240", "300", "500")), names = ""), class = "table")
解答
能否基于频率表制作散点图?
可以。报错原因是ggplot不支持直接使用一维table对象作为数据源,需先将其转换为二维数据框,并修正任务时长的数值类型(原table行名为字符型)。
具体操作步骤
转换table为数据框并处理数据
将table转为数据框后,把任务时长列从字符型转为数值型,同时添加性别标识列,最后合并两个数据集便于统一绘图:# 处理女性数据 df_female <- as.data.frame(t1) df_female$Var1 <- as.numeric(as.character(df_female$Var1)) df_female$gender <- "Female" colnames(df_female) <- c("task_duration", "frequency", "gender") # 处理男性数据 df_male <- as.data.frame(t2) df_male$Var1 <- as.numeric(as.character(df_male$Var1)) df_male$gender <- "Male" colnames(df_male) <- c("task_duration", "frequency", "gender") # 合并数据集 df_combined <- rbind(df_female, df_male)绘制散点图
基于合并后的数据集,用ggplot按性别区分颜色绘制散点图:library(ggplot2) ggplot(df_combined, aes(x = task_duration, y = frequency, color = gender)) + geom_point(size = 3) + labs(x = "任务时长(分钟)", y = "人数频率", title = "男女任务时长-频率对比散点图") + scale_color_manual(values = c("Female" = "blue", "Male" = "red")) + theme_minimal()
关键说明
- 必须将任务时长列转为数值型,否则x轴会按字符排序(如"10"会排在"2"前面),导致图表逻辑错误。
- 合并数据集后用单一
geom_point()配合color = gender映射,能更清晰地管理分组,自动生成图例。
内容的提问来源于stack exchange,提问作者Large Simpsons
相关产品推荐
相关产品推荐

