Neal Fultz
Neal Fultz

Reputation: 9687

ggplot geom_line in polar coordinates connects strangely

I want to plot r = theta from 0 to 20\pi, which should be a spiral with ten loops.

This works ok:

data.frame(x=seq(0,20*pi, length.out=1000)) %>% mutate(theta=x %% (2*pi), r=x) %>% 
ggplot() + aes(x=theta, y=r) + coord_polar(start=-pi/2, direction=-1) + 
ggtitle("r=theta") + geom_line() + ylim(0,20*pi) + xlim(0, 2*pi)

With points

But when I change the geom_point to geom_line, it connects the points strangely:

enter image description here

How can I fix this?

Upvotes: 1

Views: 755

Answers (1)

Richard Telford
Richard Telford

Reputation: 9923

The key thing to do is to set the group aesthetic to stop the lines doubling back with geom_path. Here I set things up slightly differently to avoid a gap at theta = 0

data.frame(theta = rep(seq(0, 2 * pi, length = 100), 10)) %>% 
  mutate(r = seq(0, 20 * pi, length = 1000), z = rep(1:10, each = 100)) %>%   
  ggplot() + aes(x=theta, y=r, group = z) + 
  coord_polar(start = -pi/2, direction = -1) + 
  ggtitle("r = theta") + 
  geom_path() + 
  ylim(0, 20 * pi) + xlim(0, 2 * pi)

Upvotes: 3

Related Questions