Bar chart in R

What is bar chart?

A bar chart or bar graph is a chart with rectangular bars with lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A vertical bar chart is sometimes called a column bar chart. - Wikipedia

Plotting bar chart in R

A csv sample file


name,weight
Mary,60
Chi,70
Chen,45
Jack,65
Weber,66
Kevin,80

If you compile the program via command R CMD BATCH <program> you can use read.csv('data.csv', ...) to loading the csv file. But If you are using Rstudio, you might occur some path problem, then change read.csv(file.choose(), ...) and choose your file manually.

plot()

1
2# Use file choose cause Rstudio have some path problems
3# loading csv file
4score <- read.csv('data.csv', header=TRUE, sep=",")
5# plot!
6plot(score)
7

Result:

plot

barplot()

1
2student <- read.csv(file.choose(), header=TRUE, sep=",")
3barplot(as.integer(student$weight), 
4        width = 5,
5        names.arg = student$name)
6

Result:

box plot


Advance:

 1
 2student <- read.csv(file.choose(), header=TRUE, sep=",")
 3barplot(as.integer(student$weight), 
 4        width = 5,
 5        names.arg = student$name,
 6        horiz = TRUE,
 7        border = "dark blue",
 8        col = "red",
 9        las = 1)
10

Result:

box plot2

Using ggplot2

ggplot2 is one of the most famous plotting system in R. And drawing a bar plot via ggplot2 is fairly easy.

Install


install.packages("ggplot2")

geom_bar()

 1
 2# loading ggplot2
 3library(ggplot2)
 4
 5student <- read.csv(file.choose(), header=TRUE, sep=",")
 6ggplot(data=student, aes(x=name, y=weight)) + geom_bar(stat="identity")
 7# saving the plot
 8ggsave('plot.png')
 9

Result:

Advence:

 1
 2library(ggplot2)
 3
 4student <- read.csv("data.csv", header=TRUE, sep=",")
 5ggplot(data=student, aes(x=name, y=weight)) + 
 6        geom_bar(stat="identity", fill = I("grey50")) + 
 7        guides(fill=FALSE) +
 8        xlab("Name") + ylab("Weight") +
 9        ggtitle("Student's weight")
10ggsave('plot2.png')
11

Result:


Code

Code is all available on gist


References