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

使用dplyr在两个DataFrame中生成相同变量并绘制分组对比图

处理组与对照组负面推文占比的月度趋势对比

数据结构说明

  • 对照组数据示例:
tweet sentiment   month_year
xyz   negative.   March_2022
xyz   positive.   March_2022
xyz   neutral.    March_2022
xyz   negative.   April_2022
  • 处理组数据结构与对照组一致,示例:
tweet sentiment   month_year
xyz   negative.   March_2022
xyz   positive.   March_2022
xyz   positive.    March_2022
xyz   positive.   April_2022

单组月度负面推文占比统计

统计代码

sentiment_monthly <- control_group  %>%
 group_by(month_year) |>
  summarise(sentiment_count = n(),
            negative_count = sum(sentiment_human_coded == "negative"),
            negative_share = negative_count/sentiment_count * 100) 

统计结果示例

structure(list(month_year = structure(c(2011.16666666667, 2011.25, 
2011.41666666667, 2011.75, 2011.83333333333, 2011.91666666667, 
2012.08333333333, 2012.16666666667, 2012.25, 2012.33333333333
), class = "yearmon"), sentiment_count = c(272L, 62L, 64L, 434L, 
111L, 59L, 72L, 144L, 43L, 17L), negative_count = c(27L, 23L, 
47L, 317L, 79L, 27L, 25L, 78L, 27L, 3L), negative_share = c(9.92647058823529, 
37.0967741935484, 73.4375, 73.0414746543779, 71.1711711711712, 
45.7627118644068, 34.7222222222222, 54.1666666666667, 62.7906976744186, 
17.6470588235294), year = c(2011, 2011, 2011, 2011, 2011, 2011, 
2012, 2012, 2012, 2012)), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

单组负面占比可视化代码

ggplot(data = sentiment_monthly, aes(x = as.Date(month_year), y = negative_share)) +
    geom_bar(stat = "identity", fill = "#FF6666", position=position_dodge()) + 
    scale_fill_grey() +
    scale_x_date(date_breaks = "1 month", date_labels = "%b %Y") +
    theme(plot.title = element_text(size = 18, face = "bold")) +
  theme_bw()+
   theme(axis.title.x=element_blank(),
                      axis.ticks.x=element_blank()) + # 移除x轴标签
    theme(plot.title = element_text(size = 5, face = "bold"),
          axis.text.x = element_text(angle = 90, vjust = 0.5))

两组数据合并与对比可视化代码

control_graph |> select(month_year,group, negative_share) |> 
  filter(group == "control")

treatment_graph |> select(month_year,group, negative_share) |> 
 filter(group == "treatment")

control_graph |> 
  bind_rows(treatment_graph) |> 
ggplot(aes(x = as.Date(month_year), y = negative_share, fill = group)) + 
  geom_bar(stat = "identity", position=position_dodge())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 21:50:25