Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

r - Closing the lines in a ggplot2 radar / spider chart

I need a flexible way to make radar / spider charts in ggplot2. From solutions I've found on github and the ggplot2 group, I've come this far:

library(ggplot2) 

# Define a new coordinate system 
coord_radar <- function(...) { 
  structure(coord_polar(...), class = c("radar", "polar", "coord")) 
} 
is.linear.radar <- function(coord) TRUE 

# rescale all variables to lie between 0 and 1 
scaled <- as.data.frame(lapply(mtcars, ggplot2:::rescale01))

scaled$model <- rownames(mtcars)    # add model names as a variable 

as.data.frame(melt(scaled,id.vars="model")) -> mtcarsm

ggplot(mtcarsm, aes(x = variable, y = value)) + 
    geom_path(aes(group = model)) +
    coord_radar() + facet_wrap(~ model,ncol=4) + 
    theme(strip.text.x = element_text(size = rel(0.8)), 
          axis.text.x = element_text(size = rel(0.8)))

which works, except for the fact that lines are not closed. I thougth that I would be able to do this:

mtcarsm <- rbind(mtcarsm,subset(mtcarsm,variable == names(scaled)[1]))
ggplot(mtcarsm, aes(x = variable, y = value)) + 
    geom_path(aes(group = model)) +
    coord_radar() + facet_wrap(~ model,ncol=4) + 
    theme(strip.text.x = element_text(size = rel(0.8)), 
          axis.text.x = element_text(size = rel(0.8)))

in order to join the lines, but this does not work. Neither does this:

closes <- subset(mtcarsm,variable == names(scaled)[c(1,11)])
ggplot(mtcarsm, aes(x = variable, y = value)) + 
    geom_path(aes(group = model)) +
    coord_radar() + facet_wrap(~ model,ncol=4) + 
    theme(strip.text.x = element_text(size = rel(0.8)), 
          axis.text.x = element_text(size = rel(0.8))) + geom_path(data=closes)

which does not solve the problem, and also produces lots of

"geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

messages. Som, how do I go about closing the lines?

/Fredrik

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using the new ggproto mechanism available in ggplot2 2.0.0, coord_radar can be defined as:

coord_radar <- function (theta = "x", start = 0, direction = 1) 
{
 theta <- match.arg(theta, c("x", "y"))
 r <- if (theta == "x") 
        "y"
      else "x"
 ggproto("CoordRadar", CoordPolar, theta = theta, r = r, start = start, 
      direction = sign(direction),
      is_linear = function(coord) TRUE)
}

Not sure if the syntax is perfect but it is working...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...