在ggplot2中,如何在条形图中分别绘制四组一组一个csv文件?

时间:2019-12-01 17:55:17

标签: r ggplot2 graph

我是R语言的初学者。我有一个问题。

我正在尝试将多个条形设置为enter image description here

为此,我正在使用以下数据

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

如何使用此数据制作上图? 非常感谢,

1 个答案:

答案 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")

您将获得以下图形

enter image description here

希望它能回答您的问题。

数据

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))