Multiple beside barplots with different variables in R - r

I have three lists in R like these;
> list1<-list(Joseph=12, Johan=10, Dave=15,Steve=3,Jo=8)
> list2<-list(Joseph=12, David=10,George=2,Damian=20,Louis=2)
> list3<-list(Bill=22,David=2,Peter=2,Dave=18,Sebastian=8,William=3)
each column has a name label and a numeric score.
I want to display 3 barcharts, one beside the other; each barchart plots the 3 main scored names for each list, saving the label.
For instance, the first barplot shows Dave,Joseph,Johan with heights 15,12,10. The second barplot shows Damian,Joseph and David with heights 20,12 and 10, while the third barplot shows Bill,Dave,Sebastian with heights 22,18 and 8.
I found only examples where the very same variables are plotted in multiple barplots one beside the other in different experiments, but here nominally variables might keep changing from a barplot to another.
How to achieve my goal?

Using multiplot function given in the link. I am also using ggplot2 and reshape2 :
p1<-ggplot(melt(data.frame(list1)),aes(x=variable,y=value))+geom_bar(stat='identity')
p2<-ggplot(melt(data.frame(list2)),aes(x=variable,y=value))+geom_bar(stat='identity')
p3<-ggplot(melt(data.frame(list3)),aes(x=variable,y=value))+geom_bar(stat='identity')
multiplot(p1, p2, p3, cols=1)
Another option is to use grid.arrange() in the gridExtra package:
grid.arrange(p1, p2,p3,ncol=3)

You can use par and mfcol/mfrow for this:
par(mfcol=c(1,3))
barplot(unlist(list1))
barplot(unlist(list2))
barplot(unlist(list3))
par(mfcol=c(1,1))

Related

Using lapply on a dataframe to create histograms with labels

I have created some code to generate histograms using apply on the state.x77 dataset.
attach(as.data.frame(state.x77))
lapply(X=c("Population","Income","Illiteracy","Life Exp","Murder","HS Grad","Frost","Area"),FUN=function(s)hist(state.x77[,s],main=paste("Hist of",s)))
It works fine with generating the titles for the graphs but I do not know how to create labels for the x and y-axis.
The y-axis has the label "frequency" which is fine but I want to make it so that each x-axis is labelled according to the corresponding variable in state.x77.
How would I generate the labels?
I found the answer
lapply(X=c("Population","Income","Illiteracy","Life Exp","Murder","HS Grad","Frost","Area"),FUN=function(s)hist(state.x77[,s],main=paste("Hist of",s),xlab=s))
Adding xlab=s works for the labels.

How can I stop sapply dropping my barplot titles?

I'm wanting to make a barplot for the factor variables in my data set. To do this I've been running sapply(data[sapply(data, class)=='factor'],function(x) barplot(table(x))). To my annoyance, the plots remember their factor labels, but none of them have retained a title. How can I fix this without titling each graph by hand?
Currently, I'm getting humorously vague untitled graphs like this:
How about
## extract names
fvars <- names(data)[which(sapply(data,inherits,"factor"))]
## apply barplot() with main=
lapply(fvars, function(x) barplot(table(data[[x]]), main=x))
?
Example data:
data <- mtcars
for (i in c("vs","am","gear","carb")) data[[i]] <- factor(data[[i]])
Note that this creates all the plots at once. If you're working in a GUI with a plot history (RStudio or RGui) you can page back through the graphs. Otherwise, you might want to use par(mfrow=c(nr,nc)) (fill in number of rows and columns) to set up subplots before you start.
The numbers that are returned are the bar midpoints (see ?barplot): you could wrap the barplot() call in invisible() if you don't want to see them.

Plot group in lattice, using different data sources

Using the lattice package in R, I would like to plot one row of 7 diagrams, all using the same Y-axis. The diagrams should be (vertical) line diagrams. The problem is that my data are each in 7 separate dataframes (containing X and Y data), with different slightly different limits on the Y-axis data.
Besides all tutorials, I don't get it right. What must my Code look like? Is there even a clean solution for this in lattice?
You could combine all your data frames into one and then do something like
xyplot(Y~X|odf,data=combinedDF,layout=c(7,1))
where odf is an indicator column of the original data frame. This by default should use a common y scale.
Apart from combining the data, you could create 7 separate plots, then print them.
p1 <- xyplot(Y~X,data=DF1,ylim=c(Y1,Y2))
p2 <- xyplot(Y~X,data=DF2,ylim=c(Y1,Y2))
etc.
To print:
print(p1,split=c(1,1,7,1),more=TRUE)
print(p2,split=c(2,1,7,1),more=TRUE)
...
print(p7,split=c(7,1,7,1),more=FALSE)
see ?print.trellis.
Of course, arranging single plots like this doesn't really use the features of lattice. You could just as easily do this with base graphics using layout or par(mfrow=c(1,7)) for example, and a common ylim.

positioning plots and table

I would like to plot two histograms and add a table to a pdf file. With the layout function I managed to plot the histograms (plotted them using hist function) where I want them to be but when I used grid.table function from the gridExtra package to add the table the table is laid out on the histograms and I am not able to position them properly. I have tried addtable2plot function but I dont find it visually appealing.
Any thoughts on How do I get around this?
I want my pdf to look like this
histogram1 histogram2
t a b l e
Essentially, one row with two columns and another row with just one column. This is what I did.
require(gridExtra)
layout(matrix(c(1,2,3,3),2,2,byrow=T),heights=c(1,1))
count_table=table(cut(tab$Longest_OHR,breaks=c(0,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.55,0.60,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1.00)))
ysize=max(count_table)+1000
hist(tab$Longest_OHR,xlab="OHR longest",ylim=c(0,ysize))
count_table=table(cut(tab$Sum_of_OHR.s,breaks=c(0,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.55,0.60,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1.00)))
ysize=max(count_table)+1000
hist(tab$Sum_of_OHR.s,xlab="OHR Sum",ylim=c(0,ysize))
tmp <- table(cut(tab$Length_of_Gene.Protein, breaks = c(0,100,200,500,1000,2000,5000,10000,1000000000)), cut(tab$Sum_of_OHR.s, breaks = (0:10)/10))
grid.table(tmp)
dev.off()
Any help will be appreciated.
Ram
Here's an example of how to combine two base plots and a grid.table in the same figure.
library(gridExtra)
layout(matrix(c(1,0,2,0), 2))
hist(iris$Sepal.Length, col="lightblue")
hist(iris$Sepal.Width, col="lightblue")
pushViewport(viewport(y=.25,height=.5))
grid.table(head(iris), h.even.alpha=1, h.odd.alpha=1,
v.even.alpha=0.5, v.odd.alpha=1)
The coordinates sent to viewport are the center of the panel. Too see exactly where its boundaries are you can call grid.rect().

R Lattice Plot Multiple Lines with Specific Color

I have two problems that I am having trouble to solve for. Firstly when I do a multiple column matrix plot using lattice xyplot, I find that all the points are connected. How can I get separate disconnected lines?
x<-cbind(rnorm(10),rnorm(10))
xyplot(x~1:nrow(x),type="l")
Secondly, I am having trouble figuring out how to make one line thicker than the other. For example, given that I want column 1, then column 1's line will be thicker than that of column 2.
The lattice plotting paradigm,like that of ggplot2 that followed it, expects data to be in long format in dataframes:
dfrm <- data.frame( y=c(rnorm(10),rnorm(10)),
x=1:10,
grp=rep(c("a","b"),each=10))
xyplot(y~x, group=grp, type="l", data=dfrm, col=c("red","blue"))
This might not be the most elegant solution but it gets the job done:
x<-cbind(rnorm(10),rnorm(10))
plot1<-xyplot(x[,1]~1:nrow(x),type="l",col="red",lwd=3)
plot2<-xyplot(x[,2]~1:nrow(x),type="l")
library(latticeExtra)
plot1+plot2
I assumed that you wanted V1 and V2 plotted against the number of observations.
Otherwise you indeed only have one line.
You can adjust the axis and labels according to taste.

Resources