【发布时间】:2022-12-06 02:21:25
【问题描述】:
我将治疗组和对照组分别存储在两个 df 中。 我有兴趣在同一图表中为两组呈现两个变量 1) 情绪和 2) month_year。 df 中的每一行代表一条推文,后跟预测的情绪和写入它的 month_year。例如,在对照组中,数据如下所示:
tweet sentiment month_year
xyz negative. March_2022
xyz positive. March_2022
xyz neutral. March_2022
xyz negative. April_2022
同样,治疗组 df 的结构如下:
tweet sentiment month_year
xyz negative. March_2022
xyz positive. March_2022
xyz positive. March_2022
xyz positive. April_2022
我很感兴趣地计算两个群体之间每月负面推文的份额。
这是我为一组创建图表的尝试。但是,我有兴趣在下面生成相同的指标,但同时为两个组生成,这样我就可以在同一个图表中显示它们,我可以在其中比较两个组在整个时间内的趋势。
创建一个变量计数 1-负面情绪帖子和 2-他们每月的份额
sentiment_monthly <- control_group %>%
group_by(month_year) |>
#group_by(treatment_details) |>
summarise(sentiment_count = n(),
negative_count = sum(sentiment_human_coded == "negative"),
negative_share = negative_count/sentiment_count * 100)
以下是“情绪月刊”pdf的数据示例:
dput(sentiment_monthly[1:5],)
输出:
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()) + # remove x-axis label
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())
但是,我不断收到此错误消息
“bind_rows() 中的错误:
!无法组合 ..1$month_year 和 ..2$month_year 。
回溯:
- ggplot2::ggplot(...)
- dplyr::bind_rows(control_graph, treatment_graph)
- vctrs::vec_rbind(!!!dots, .names_to = .id) bind_rows(control_graph, treatment_graph) 错误:”
【问题讨论】:
-
您在寻找分组条形图吗?
标签: r ggplot2 dplyr graph tidyverse