R 使用ggplot2的条形图

R 使用ggplot2的条形图,r,ggplot2,bar-chart,R,Ggplot2,Bar Chart,我有这样一个数据集: cars trucks suvs 1 2 4 3 5 4 6 4 6 4 5 6 9 12 16 我正试图为这些数据画一个条形图。目前,我可以使用条形图: barplot(as.matrix(autos_data), main="Autos", ylab= "Total",beside=TRUE, col=rainbow(5))

我有这样一个数据集:

cars    trucks  suvs
1          2    4
3          5    4
6          4    6
4          5    6
9          12   16
我正试图为这些数据画一个条形图。目前,我可以使用
条形图

barplot(as.matrix(autos_data), main="Autos", 
         ylab= "Total",beside=TRUE, col=rainbow(5))
生成此图形:

因此,我的问题是: 我能用ggplot2画这样的图吗?具体来说-如何使用刻面或其他选项按一周中的天数分割图形? 如果是,我如何做到这一点?
此外,如何使用facet生成不同的布局?

这是以前多次提出的问题。答案是您必须使用
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")

dat这里是与
tidyr

这里最大的问题是您需要将数据转换为整洁的格式。我强烈推荐阅读R for Data Science(),使您能够使用整洁的数据和ggplot启动并运行

一般来说,一个好的经验法则是,如果您必须输入同一几何图形的多个实例,可能有一种数据格式的解决方案,可以让您将所有内容都放在顶级
ggplot()
中的
aes()
函数中。在这种情况下,您需要使用
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")
库(tidyverse)
#我在重新创建你的数据时遇到了一些问题,所以我只是在这里自己做了

data-1没有在屏幕右上角的便利搜索框中搜索“barplot ggplot2”。我尝试在谷歌和本网站中搜索。事实上,我可以使用ggplot2为原始数据绘制条形图。因为ggplot2可以为您计算数字。问题是,如果您已经得到了计数结果,如何使用ggplot2像一般的“条形图”命令一样绘制条形图?好的,这更合理。现在在你的问题中再加上这些补充信息,我将改变我的反对票。并添加一些示例代码,例如,显示您所做的工作和遇到的问题。可能重复的