【问题标题】:Make two geom_bar() plots base on different columns in one plot根据一个图中的不同列制作两个 geom_bar() 图
【发布时间】:2020-09-16 23:58:53
【问题描述】:

我有一个如下所示的数据框:

 Year     Women       Men
1 2013    145169      889190
2 2014    119064      849778
3 2015    210107     1079592
4 2016    221217     1427639
5 2017    205000     1692592
6 2018    273721     1703456
7 2019    434407     2010493

我想制作一个 geom_bar,其中 x 是一年,并且每年有两个栏代表女性和男性的数字。我找到了一个解决方案,这个表应该看起来不同,但我想知道是否有一个选项可以使用这个表。谢谢你的帮助:)

【问题讨论】:

  • 到目前为止您尝试过什么?你有代码吗?请在问题中也包括代码,并在谷歌上搜索“ggplot2 数据长到宽和堆叠条形图”
  • 它是从宽到长的旋转......像下面的答案应该没问题。你不需要整个 tidyverse 包.. tidyr 和 ggplot2 就足够了
  • 这能回答你的问题吗? Grouped bar plot in ggplot
  • 非常感谢您的帮助,下面的答案完美无缺。

标签: r ggplot2 geom-bar


【解决方案1】:

您可以使用以下代码

library(tidyverse)

df %>% 
      pivot_longer(cols = -c(Year,Sl), values_to = "Value", names_to = "Name") %>% 
      ggplot(aes(x = Year, y = Value, fill = Name))+geom_col(position = "dodge")

数据

df = structure(list(Sl = 1:7, Year = 2013:2019, Women = c(145169L, 
119064L, 210107L, 221217L, 205000L, 273721L, 434407L), Men = c(889190L, 
849778L, 1079592L, 1427639L, 1692592L, 1703456L, 2010493L)), class = "data.frame", row.names = c(NA, 
-7L))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-22
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2013-10-03
    相关资源
    最近更新 更多