Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R lattice bar chart: choose order of bars?

Tags:

r

lattice

My data looks like this:

service,rating_1,rating_2,rating_3,rating_4,rating_5
renew_patent,0,0,1,2,11
apply_benefit,21,20,121,828,1744
apply_employment_tribunal,0,0,0,0,0

I want R to print me a histogram for each row, with the columns as the bars of the histogram.

I've got this so far:

require(lattice)
data <- read.csv("test.csv", header = TRUE)
colors = c('red', 'orange', 'yellow', 'blue', 'green')
barchart(rating_1+rating_2+rating_3+rating_4+rating_5 ~ service, data=data, 
  auto.key=list(space='right'), scales=list(x=list(rot=45)), 
  ylab="Percentage of total", col=colors)

It's working, but it's printing the histogram with bars in alphabetical order, not the order they're specified in the CSV file.

How can I change this so the bars are in the order in the CSV file, with renew_patent first?

like image 372
Richard Avatar asked Mar 20 '23 16:03

Richard


1 Answers

You need to specify the order of the levels in the data itself, then barchart will do what you want.

One option would be to run code like:

data$service <- factor(data$service, levels=unique( as.character(data$service) ) )

before calling barchart.

like image 63
Greg Snow Avatar answered Mar 24 '23 05:03

Greg Snow