我是R语言的初学者。我有一个问题。
为此,我正在使用以下数据
gender party likes_count
<chr> <chr> <dbl>
1 F D 587.
2 F R 180.
3 M D 335.
4 M R 177.
gender party comments_count
<chr> <chr> <dbl>
1 F D 155.
2 F R 18.2
3 M D 71.7
4 M R 34.6
gender party haha_count
<chr> <chr> <dbl>
1 F D 84.4
2 F R 81.9
3 M D 53.8
4 M R 64.7
gender party wow_count
<chr> <chr> <dbl>
1 F D 84.4
2 F R 81.9
3 M D 53.8
4 M R 64.7
如何使用此数据制作上图? 非常感谢,
答案 0 :(得分:2)
对于您的问题,您正在寻找facetting
图。关于这个问题,有很多关于SO的问题/答案。
为了获取图形,首先必须操纵数据集以便准备使用ggplot2进行绘制。
library(tidyverse)
df <- df %>% pivot_longer(., -c(gender,party),names_to = "Variable", values_to = "Value") %>% mutate(New_Col = paste0(party, "-",gender))
df$Variable = factor(df$Variable, levels = c("likes", "comments", "haha", "wow"))
然后进行绘图,您可以:
library(ggplot2)
ggplot(df, aes(x = New_Col, y = Value, fill = New_Col)) +
geom_bar(stat = "identity", position = position_dodge())+
facet_wrap(.~ Variable, scales = "free")
您将获得以下图形
希望它能回答您的问题。
数据
df = data.frame(gender = c("F","F","M","M"),
party = c("D","R","D","R"),
likes = c(587,189,335,177),
comments = c(155,18.2,71.7,34.6),
haha = c(84.4,81.9,53.8,64.7),
wow = c(84.4,81.9,53.8,64.7))