Coloured horizontal bar graphs

R is great for creating some acceptable looking graphs, much more so that GnuPlot (which is also awesome ). R plots are decent, however there is a library called ggplot that is even better. I wanted to create some simple graphs of data and add a little colour – red for +ve values, blue for -ve. This is fairly simple to achieve with R and ggplot.

I can’t share the data that I am using or explain what it is. I load file content into a data.frame and then use the names to extract a entry of interest.


setwd("path/to/data/dir")
library(ggplot2)

data <- read.table("data", h=T, sep=",")

This reads the data in.


plot <- ggplot(data, aes(fill=componentToFill, x=X, y=component)) + 
geom_bar() +
coord_flip() + 
scale_y_continuous("") + 
scale_x_discrete("") + 
scale_fill_gradient2(low="blue", high="red")

component and componentToFill are things in your data frame, again I’ve had to change my names despite the fact you don’t have the data (I don’t want to get in trouble).


ggsave(filename="example.jpg", p, dpi=1000, width=7, height=5)

It’s probably a good idea to look at the plot, in this case we will save to a file called example.jpg.

The image I had looks like this.

Image
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s