barplot using ggplot2

99封情书 提交于 2019-12-17 09:43:26

问题


I have a data set like this:

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

I'm trying to draw a bar chart for this data. Currently, I can do it with barplot:

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

Generating this graph:

So my questions are: Can I use ggplot2 to draw such a graph? Specifically - how do I use faceting or other options to split the graph by days of the week? If yes, how do I accomplish that? Additionally, how do I use facet to produce a different layout?


回答1:


This has been asked many times before. The answer is that you have to use stat="identity" in geom_bar to tell ggplot not to summarise your data.

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:


Here's with tidyr:

The biggest issue here is that you need convert your data to a tidy format. I highly recommend reading R for Data Science (http://r4ds.had.co.nz/) to get you up and running with tidy data and ggplot.

In general, a good rule of thumb is that if you have to enter multiple instances of the same geom, there's probably a solution in the format of your data which would enable you to put everything in the aes() function within the top level ggplot(). In this case you need to use the gather() to arrange your data appropriately.

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")



来源:https://stackoverflow.com/questions/10352894/barplot-using-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!