Reputation: 70
Is it possibile to attach titles via an apply-family function to a series of histograms where the titles are picked from a list?
The code below creates three histograms. I want to give each a different name from a list (named "list"), in order. How do I do this?
data <- read.csv("outcome-of-care-measures.csv")
outcome <-data[,c(11,17,23)]
out <- apply(outcome, 2,as.data.frame)
par(mfrow=c(3,1))
apply(outcome,2, hist, xlim=range(out,na.rm=TRUE), xlab="30 day death rate")
Upvotes: 2
Views: 1445
Reputation: 60944
I'd use facet_wrap
from ggplot2
to get this done. ggplot2
supports this kind of plots very painlessly:
library(ggplot2)
theme_set(theme_bw())
df = data.frame(values = rnorm(3000), ID = rep(LETTERS[1:3], each = 1000))
ggplot(df, aes(x = values)) + geom_histogram() + facet_wrap(~ ID)
To change the text in the box above each facet, simply replace the text in the ID
variable:
id_to_text_translator = c(A = 'Facet text for A',
B = 'Facet text for B',
C = 'Facet text for C')
df$ID = id_to_text_translator[df$ID]
I would recommend taking a close look at what happens in these two lines. Using vectorized subsetting to perform this kind of replacement has compact syntax and high performance. Replacing this code would require a for
or apply
loop combined with a set of if
statements would make the code much longer and slower.
Another option is to directly influence the levels
of ID
, which is a factor
:
levels(df$ID) = id_to_text_translator[levels(df$ID)]
This is a lot faster, especially on datasets with a lot of rows. In addition, it keeps ID
a factor
, while the previous solution makes ID
a character
vector.
The resulting plot:
ggplot(df, aes(x = values)) + geom_histogram() + facet_wrap(~ ID)
Upvotes: 2
Reputation: 11431
As it is not only the columns but another argument that changes, you may use mapply
to have a function from the apply
family.
args <- list(xlim=range(data, na.rm=TRUE), xlab="30 day death rate")
titles <- list("Title 1", "Title 2", "Title 3")
par(mfrow=c(3,1))
mapply(hist, data, main=titles, MoreArgs=args)
If you wrap the invisible
function around the last line you can avoid the console output.
Note: I think using loops here is far more straightforward.
Upvotes: 1