You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R语言中可视化年度新闻产出的min、max、mean、median数据

问题1:CSV读取代码是否正确?

你的读取代码是正确的,只要文件路径准确、CSV格式规范(逗号分隔、首行是表头),就能成功读取数据。不过有个小细节可以优化:year字段是年份整数,你当前用colClasses = "numeric"会把它存为数值型,若想让它保持整数类型,可以调整参数:

w <- read.table("C:/Users/shall/Desktop/minmaxmeanmedian.csv", 
                sep= ",", header=TRUE, 
                colClasses = c("integer", rep("numeric", 4)))

如果用tidyverse里的read_csv会更高效,且自动识别列类型,代码更简洁:

library(readr)
w <- read_csv("C:/Users/shall/Desktop/minmaxmeanmedian.csv")
问题2:绘制目标图表的正确方法

你的现有代码存在几个问题:错误引用了未定义的table1(应该用你的数据框w)、数据重塑方向错误(需要把宽格式转成长格式,而非反向转换)、选择了不符合需求的箱线图类型。

要实现“X轴为年份,Y轴为新闻数量,展示每年四个统计值”的效果,可按以下步骤操作:

  1. 把宽格式数据转成长格式:用pivot_longer将max/min/median/mean列合并为“统计量名称”和“对应数值”两列
  2. 用ggplot绘制,以年份为X轴,数值为Y轴,用颜色/形状区分不同统计量

完整代码(展示所有统计量的年度变化)

library(tidyverse)
# 读取数据
w <- read_csv("C:/Users/shall/Desktop/minmaxmeanmedian.csv")

# 转换为长格式
w_long <- w %>% 
  pivot_longer(cols = -year, 
               names_to = "statistic", 
               values_to = "news_count")

# 绘制图表
ggplot(w_long, aes(x = year, y = news_count, color = statistic, shape = statistic)) +
  geom_point(size = 3) +  # 用点展示每个统计值
  geom_line(aes(group = statistic)) +  # 用线连接同统计量的年度变化(可选)
  labs(x = "年份", 
       y = "新闻数量", 
       color = "统计指标", 
       shape = "统计指标") +
  theme_minimal() +
  theme(legend.position = "right")

备选样式(展示范围+核心统计值)

如果想要突出min-max范围,同时标记中位数和均值,可用以下代码:

ggplot(w, aes(x = year)) +
  # 绘制min到max的误差线
  geom_errorbar(aes(ymin = min, ymax = max), width = 0.2) +
  # 标记中位数和均值
  geom_point(aes(y = median, color = "中位数"), size = 3) +
  geom_point(aes(y = mean, color = "平均值"), size = 3) +
  labs(x = "年份", 
       y = "新闻数量", 
       color = "统计指标") +
  theme_minimal()

内容的提问来源于stack exchange,提问作者Sam Hall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 01:32:09