Rotate x-axis text when using coord_polar()

I understand this is an old topic, but I found a better solution for this problem, inspired from baptise's comment:

ggplot(data, aes(x=someId, y=someValue)) +
  geom_point() + 
  coord_polar() +
  theme(axis.text.x = element_text(
    angle= -90 - 360 / length(unique(data$someId)) * seq_along(data$someId)
    )
  )

The answer by Yoplait helps a lot, but still does not solve the issue of having to read upside down in half of the graph. An extention of the idea that this poster proposes is as follows.

First prepare the angle vector, making sure we split the graph in two:

sequence_length = length(unique(data$someId))
first_sequence = c(1:(sequence_length%/%2)) 
second_sequence = c((sequence_length%/%2+1):sequence_length) 
first_angles = c(90 - 180/length(first_sequence) * first_sequence)
second_angles = c(-90 - 180/length(second_sequence) * second_sequence)

And now we can append the angle vectors to make the actual graph:

ggplot(data, aes(x=someId, y=someValue)) +
  geom_point() + 
  coord_polar() +
  theme(axis.text.x = element_text(
    angle= c(first_angles,second_angles)
    )
  )

here is a not elegant example of the coordinate:

CoordPolar2 <- proto(CoordPolar, {
  objname <- "polar2"
  guide_foreground <- function(., details, theme) {
    theta <- .$theta_rescale(details$theta.major, details)
    labels <- details$theta.labels

    # Combine the two ends of the scale if they are close
    theta <- theta[!is.na(theta)]
    ends_apart <- (theta[length(theta)] - theta[1]) %% (2*pi)
    if (ends_apart < 0.05) {
      n <- length(labels)
      if (is.expression(labels)) {
        combined <- substitute(paste(a, "/", b), 
          list(a = labels[[1]], b = labels[[n]]))
      } else {
        combined <- paste(labels[1], labels[n], sep="/")
      }
      labels[[n]] <- combined
      labels <- labels[-1]
      theta <- theta[-1]
    }

    grobTree(
      if (length(labels) > 0) {
        lab <- theme_render(
          theme, "axis.text.x", 
          labels, 0.45 * sin(theta) + 0.5, 0.45 * cos(theta) + 0.5,
          hjust = 0.5, vjust = 0.5,
          default.units="native"
        )
        lab$rot <- (pi/2 - theta) / pi * 180
        lab
      },
      theme_render(theme, "panel.border")
    )
  }
})

coord_polar2 <- CoordPolar2$build_accessor()

p <- qplot(data=presidential, name,end) + coord_polar2()
print(p)

enter image description here

Tags:

R

Ggplot2