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

zac*_*ach 6 r ggplot2

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

编辑提供一个例子:

qplot(data=presidential, name,end) + coord_polar()
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

小智 14

我知道这是一个古老的话题,但是我从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)
    )
  )
Run Code Online (Sandbox Code Playgroud)


FvD*_*FvD 8

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)
Run Code Online (Sandbox Code Playgroud)

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

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


koh*_*ske 5

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

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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明