Add line segments to polar histogram in ggplot2

362 views
Skip to first unread message

Kent Johnson

unread,
Apr 26, 2016, 9:40:38 PM4/26/16
to ggplot2
Enter code here...

(This is a duplicate of a StackOverflow question that has not been answered. See http://stackoverflow.com/q/36818235/80626 for a version with pictures...)

I am trying to make a polar histogram in ggplot2 with annotation lines which are not radial lines. 

The simple approach with `coord_polar` gives curved lines:

library(ggplot2)

d
= data.frame(x=rep(seq(0, 350, 10), times=1:36))
               lines
= data.frame(x = c(40, 90, 150, 220, 270),
               y
= c(20, 20, 20, 20, 20),
               xend
= c(115, 165, 225, 295, 345),
               yend
= c(5, 5, 5, 5, 5))
   
ggplot
(d, aes(x)) + geom_histogram(binwidth=10) +
  geom_segment
(data=lines, aes(x, y, xend=xend, yend=yend), color='red') +
  coord_polar
() + scale_x_continuous(limits=c(0, 360))



Second try uses `coord_radar`, from various sources on StackOverflow and mail lists:

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)
}
   
ggplot
(d, aes(x)) + geom_histogram(binwidth=10) +
  geom_segment
(data=lines, aes(x, y, xend=xend, yend=yend), color='red') + coord_radar()



This fails completely...

I can get the lines to draw if I use grouped lines instead of segments:

lines2 = data.frame(x = c(40, 115, 90, 165, 150, 225, 220, 295, 270, 345, 330, 45),
y
= c(20, 5, 20, 5, 20, 5, 20, 5, 20, 5, 20, 5),
group = c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6))
   
ggplot
(lines2, aes(x, y, group=group)) + geom_line(color='red') + coord_radar() +
  scale_y_continuous
(limits=c(0, 36)) + scale_x_continuous(limits=c(0, 360))



but I still need the histogram...

Any ideas? Thanks!
Kent Johnson


Thomas

unread,
Apr 27, 2016, 11:13:48 AM4/27/16
to ggplot2
This might not be the answer you're hoping for, but here goes:

ggforce (https://github.com/thomasp85/ggforce), which will arrive on CRAN within the coming months, have a eom_arc_bar that can be used to draw pies, donuts, windroses etc. without the need for using coord_polar, that is it draws arcs in cartesian space. There is currently no implementation for automatically generating histogram values though, so you'll need to calculate these apriori. Also, as there is no coordinate transformation the x- and y-axes are pretty meaningless, but this is usually not a problem for radial layouts.

Using this approach you can add additional annotation and geoms on top that relies on a cartesian coordinate system...

best

Thomas
Reply all
Reply to author
Forward
0 new messages