Ivan Popivanov
2013-Jan-02 18:56 UTC
[R] How to use geom_line (from ggplot) with aesthetics in a function?
Hello,
I have been struggling with this for a while, tried a few things, but no
clean solution so far. Here is an example from the documentation for
geom_line:
=========================================# Summarise number of movie ratings by
year of movie
mry <- do.call(rbind, by(movies, round(movies$rating), function(df) {
nums <- tapply(df$length, df$year, length)
data.frame(rating=round(df$rating[1]), year = as.numeric(names(nums)),
number=as.vector(nums))
}))
p <- ggplot(mry, aes(x=year, y=number, group=rating))
p + geom_line()
# Add aesthetic mappings
p + geom_line(aes(size = rating))
p + geom_line(aes(colour = rating))
=========================================
Notice the last two lines, "size = rating" and "colour =
rating", this has
knowledge of the structure of the data frame. My goal is to write a generic
function, which takes a few vectors and a few strings (column names) as
arguments, builds the data frame and then produces a chart. Building the
data frame is easy, but how should this function look like in the geom_line
code? The only solution which I found is something along the lines:
for( ii in indicatorNames ) {
gg = gg + geom_line( aes_string( x="DATE", y=ii, color=paste(
sep="",
"\"", ii, "\"" ) ), size=0.75 )
}
Where indicatorNames is the name of the columns and DATE is the first
column of the data frame. What I don't like, not to mention I understand
completely, is the color=paste( sep="", "\"", ii,
"\"" ) - is this the
right solution for this purpose? Am I missing something?
Thanks in advance,
Ivan
[[alternative HTML version deleted]]
Maybe Matching Threads
- zuzufarah Help with ggplot 2 error: Aesthetics must either be length one, or the same length as the dataProblems
- ggplot2/aesthetic plotting advice
- ggplot- using geom_point and geom_line at the same time
- ggplot: geom_line with only pairs of points connected
- Add a vertical arrow to a time series graph using ggplot and xts
