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

使用ggplot2实现情感随时间变化可视化及x轴日期格式调整

R语言情感随时间变化占比可视化实现

数据集结构

首先查看数据集前6行的代码:
head(Visualizing_sentiment)

返回数据样例:

date         sentiment
<S3: POSIXct> <chr>
2011-12-01    neutral         
2011-12-01    negative            
2011-12-01    negative            
2011-12-01    negative            
2011-12-01    negative            
2011-12-01    negative

遇到的问题

最初的可视化代码如下,无法实现x轴日期格式为月/年的需求:

Visualizing_sentiment %>% 
    gather(sentiment, values, -date) %>%
    ggplot() +
    geom_bar(aes(y = values, x = date, fill = sentiment), stat = "identity")

尝试用以下代码将POSIXct格式的date字段转换为Date类:

lubridate::ymd('20111201')
lubridate::ymd(20111201)
lubridate::ymd(Visualizing_sentiment$date)

转换完成后运行绘图代码报错,报错代码如下:

Visualizing_sentiment %>% 
    gather(sentiment, values, -date) %>%
    ggplot() +
    scale_x_date(date_breaks = "1 month", date_labels =  "%b %Y") +
    theme(axis.text.x=element_text(angle=60, hjust=1)) +
    geom_bar(aes(y = values, x = date, fill = sentiment), stat = "identity")

核心需求

生成柱状图,展示每个年月对应的消极、中性、积极三类情感的占比情况,预期为按年份分面的堆叠柱状图样式。

可运行的最终实现代码

library(tidyverse)
library(lubridate)

Visualizing_sentiment %>%
  # 将日期转换为Date格式适配scale_x_date
  mutate(date = as.Date(date)) %>%
  # 按日期和情感分类统计样本数量
  count(sentiment, date) %>%
  ggplot(aes(x = date, y = n, fill = sentiment)) +
  # position="fill" 展示占比,需要展示原始数量可以去掉该参数,需要并列柱状图替换为position="dodge"
  geom_col(position = "fill") +
  # 自定义情感分类对应颜色
  scale_fill_manual(values = c("positive" = "green", 
                               "negative" = "red", 
                               "neutral"= "black")) +
  # 设置x轴日期显示格式为 月-年
  scale_x_date(date_labels = "%b-%y") +
  # 按年份分面展示
  facet_wrap(~ year(date)) +
  theme_classic()

问题原因说明

  • 原始数据集已经是长格式,不需要调用gather做长宽转换,强行转换会导致y轴映射的values字段类型错误,是报错的核心原因
  • 绘制情感计数/占比柱状图需要先按日期、情感分类做分组计数,不能直接映射原始行数据到y轴
  • 要展示占比只需将geom_col的position参数设置为fill即可自动计算每组内的占比

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:45:01