使用coord_polar()时在ggplot2中旋转x轴文本

时间:2011-10-20 01:04:53

标签: r ggplot2

我正在使用ggplot2绘制极轴上的许多值的散点图 - coord_polar()。生成的图形具有拥挤的文本,因为文本始终与页面底部对齐。是否可以放置文本,使其沿极轴x轴径向打印?

编辑提供示例:

qplot(data=presidential, name,end) + coord_polar()

在总统大选中,我希望看到总统的名字与他们所在的轴/轮对齐。下面是我正在处理的图表示例,其中x轴是分类,y轴是连续变量(类似于示例)。

enter image description here

3 个答案:

答案 0 :(得分:12)

我理解这是一个古老的话题,但我从baptise的评论中找到了一个更好的解决这个问题的方法:

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)
    )
  )

答案 1 :(得分:7)

Yoplait的答案有很多帮助,但仍然无法解决在图表的一半中阅读颠倒的问题。本海报提出的想法的扩展如下:

首先准备角度矢量,确保我们将图形分成两部分:

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)

现在我们可以附加角度向量来制作实际的图形:

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

答案 2 :(得分:3)

这是坐标的一个不优雅的例子:

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