繁体   English   中英

使用ggplot2的barplot

[英]barplot using ggplot2

我有一个这样的数据集:

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

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

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

生成此图:

条形图

所以我的问题是:我可以使用ggplot2绘制这样的图形吗? 具体来说-如何使用构面或其他选项按星期几划分图表? 如果是,我该怎么做? 此外,如何使用构面来产生不同的布局?

这已经被问过很多次了。 答案是您必须在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")

在此处输入图片说明

这是和tidyr

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

通常,一个好的经验法则是,如果您必须输入同一geom的多个实例,则可能存在一种数据格式的解决方案,该解决方案使您可以将所有内容放入顶级ggplot()中的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")

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM