Bar charts

Bar charts can be used to compare data across a given x axis. Often the x axis could represent a temporal value such as time, date, and so on. It is useful as a visualization to see how quantities changed along a certain timeline or with respect to the variable in the x axis.

Although they may appear similar to histograms, the main difference in this case is that bar plots can be, and often are, used to represent data beyond simply count information. For instance, if we had to plot the number of convicts per year from the Hartnagel dataset, plotting with a histogram on year will simply yield a count of rows by year. Instead, we can use a bar chart as follows.

The example here uses ggplot2 to display the bar chart:

ggplot(Hartnagel, aes(year,mconvict,fill=as.factor
(year - round(year%%10)))) + geom_bar(stat="identity") +
scale_fill_discrete(name = "Decade") + xlab("Decade")
+ ylab ("Number of Convicts")

Note that it is fairly simple to draw the same chart with horizontal bars, as follows:

 
ggplot(Hartnagel, aes(year,mconvict,fill=as.factor
(year - round(year%%10)))) + geom_bar(stat="identity") +
scale_fill_discrete(name = "Decade") + xlab("Decade") +
ylab ("Male indictable-offense conviction rate per 100,000") +
coord_flip()

This is especially useful when there are several variable names, the names are long, or the data would be better represented in a horizontal format:

 

ggplot2 is very sophisticated and hundreds of other chart types can be drawn using basic commands. The following is a stacked bar chart, similar to the ones before, except that the color is based on gender male versus female conviction rate:

hm <- melt(Hartnagel, id.vars="year",measure.vars=c("mconvict","fconvict"), variable.name="gender",value.name="convict") 
 
ggplot(hm, aes(year,convict,fill=as.factor(gender))) +
geom_bar(stat="identity") + scale_fill_discrete(name = "Gender") +
xlab("Decade") + ylab ("Number of Convicts")

The output is as follows:

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.159.235