【问题标题】:I am using ggplot2 to make a bar chart and can't get the years correct along the x-axis我正在使用 ggplot2 制作条形图,并且无法沿 x 轴获得正确的年份
【发布时间】:2018-01-11 00:14:51
【问题描述】:

我正在使用 ggplot2 制作按性别划分的每年参与者数量的条形图。如果我包括 14 年,我希望每年有 2 个条形图,对应于当年的男性和女性人数。我不是每年都在 x 轴上。我认为数据正在被分箱。我尝试使用 scale_x_date 更改 bin 宽度,但仍然卡住。 你能帮我弄清楚如何在我的图表中显示每一年的数据吗?

例如,这是我 2004-2017 年的数据:

year=c(2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017)
gender=c("male" , "female")

参与者按性别分,每年分别为男性和女性:

Participants=c(1307,443,1847,630,2109,765, 1824,691,2250,952,3123,1421,4097,1904,6415,3284,8788,4678,11581,6694,13141,8478,16389,10575,20990,13811,26951,19729)
data=data.frame(year,gender,Participants)

这是我尝试生成情节的方式:

MyPlot <- ggplot(data, aes(fill=gender, y=Participants, x=year)) + 
                 geom_bar(position="dodge", stat="identity",width = .8)

print(MyPlot + ggtitle("Annual Number of Participants by Gender"))

在 x 轴上,标记了 2006、2010、2014 和 2018 年,条形对应于两年的数据。我想要每年的数据,包括条形和 x 轴上的刻度。

任何帮助将不胜感激!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    你的参与者比几年多,所以你没有一个清晰的数据框设计来作为 ggplot 的输入。

    从这里开始: 阅读:https://cran.r-project.org/web/packages/tidyr/vignettes/tidy-data.html

    其中的关键是:

    Each variable forms a column.
    Each observation forms a row.
    Each type of observational unit forms a table.
    

    然后,一旦你有一个 tibble/数据框,你的 ggplot2 代码应该可以正常工作。我会杀死 width= 选项,直到你让它工作。

    【讨论】:

      猜你喜欢
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多