【问题标题】:barplot using ggplot2使用ggplot2的条形图
【发布时间】:2018-08-10 22:50:34
【问题描述】:

我有一个这样的数据集:

cars    trucks  suvs
1          2    4
3          5    4
6          4    6
4          5    6
9          12   16

我正在尝试为这些数据绘制条形图。目前,我可以使用barplot

barplot(as.matrix(autos_data), main="Autos", 
         ylab= "Total",beside=TRUE, col=rainbow(5))

生成此图:

所以我的问题是: 我可以使用 ggplot2 来绘制这样的图表吗?具体来说 - 我如何使用分面或其他选项按星期几拆分图表? 如果是,我该如何做到这一点? 另外,如何使用 facet 来生成不同的布局?

【问题讨论】:

  • -1 表示没有在屏幕右上角的便捷搜索框中搜索“barplot ggplot2”。
  • 我尝试在谷歌和这个网站上搜索。事实上,我可以使用 ggplot2 为我的原始数据绘制条形图。因为 ggplot2 可以为你数数。问题是如果你已经得到了计数结果,如何像一般的“barplot”命令一样使用ggplot2绘制条形图?
  • 好的,这样比较明智。现在将这些附加信息添加到您的问题中,我将改变我的反对意见。并添加一些示例代码,即显示你做了什么以及你卡在哪里。

标签: r ggplot2 bar-chart


【解决方案1】:

这已经被问过很多次了。答案是你必须在geom_bar 中使用stat="identity" 来告诉ggplot 不要汇总你的数据。

dat <- read.table(text="
cars    trucks  suvs
1   2   4
3   5   4
6   4   6
4   5   6
9   12  16", header=TRUE, as.is=TRUE)
dat$day <- factor(c("Mo", "Tu", "We", "Th", "Fr"), 
             levels=c("Mo", "Tu", "We", "Th", "Fr"))

library(reshape2)
library(ggplot2)

mdat <- melt(dat, id.vars="day")
head(mdat)
ggplot(mdat, aes(variable, value, fill=day)) + 
  geom_bar(stat="identity", position="dodge")

【讨论】:

    【解决方案2】:

    这里是tidyr:

    这里最大的问题是您需要将数据转换为整洁的格式。我强烈建议您阅读 R for Data Science (http://r4ds.had.co.nz/),让您开始使用整洁的数据和 ggplot。

    一般来说,一个好的经验法则是,如果您必须输入同一个 geom 的多个实例,则可能有一个解决方案采用数据格式,可以让您将所有内容放在 aes() 函数中顶级ggplot()。在这种情况下,您需要使用gather() 来适当地安排您的数据。

    library(tidyverse)
    
    # I had some trouble recreating your data, so I just did it myself here
    data <- tibble(type = letters[1:9], 
                   repeat_1 = abs(rnorm(9)), repeat_2  
                   =abs(rnorm(9)), 
                   repeat_3 = abs(rnorm(9)))
    
    data_gathered <- data %>%
      gather(repeat_number, value, 2:4)
    
    ggplot(data_gathered, aes(x = type, y = value, fill = repeat_number)) +
    geom_col(position = "dodge")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-27
      • 2021-04-24
      • 2015-01-03
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      相关资源
      最近更新 更多