r - 在 R 中向饼图添加标签...辐射 "spokes"?

标签 r charts ggplot2 pie-chart

有没有办法(可能使用 ggplot 或其他一些包)在 R 中调整饼图的标签的角度?例如,此代码(使用 R 默认值):

data <- c(4,9,2,5)
names <- c("alpha","beta","gamma","delta")
pie(data,names)

创建此饼图:
enter image description here

我想要的是这样的饼图(我在 PhotoShop 中创建的非常粗略):
enter image description here

最佳答案

正如@agstudy 指出的,您需要修改函数体以创建自己的 pie功能。确实,pie不返回任何值,因此您不知道标签的确切位置和角度。

首先,你可以得到pie的正文与 graphics::pie
在函数结束时,饼图绘制为:

for (i in 1L:nx) {
    n <- max(2, floor(edges * dx[i]))
    P <- t2xy(seq.int(x[i], x[i + 1], length.out = n))
    polygon(c(P$x, 0), c(P$y, 0), density = density[i], angle = angle[i], 
        border = border[i], col = col[i], lty = lty[i])
    P <- t2xy(mean(x[i + 0:1]))
    lab <- as.character(labels[i])
    if (!is.na(lab) && nzchar(lab)) {
        lines(c(1, 1.05) * P$x, c(1, 1.05) * P$y)
        text(1.1 * P$x, 1.1 * P$y, labels[i], xpd = TRUE, 
             adj = ifelse(P$x < 0, 1, 0), ...)
    }
}

您感兴趣的部分是以下内容text ,您可以在其中指定旋转它们的角度(就像@agstudy 所做的那样)。为了使用正确的角度,你必须计算它(这是我的答案变得与另一个不同的部分......)。
实际上,它已经在绘图之前计算出来了,使用:
t2xy <- function(t) {
    t2p <- twopi * t + init.angle * pi/180
    list(x = radius * cos(t2p), y = radius * sin(t2p))
}

你只需要让这个函数也输出角度:
t2xy <- function(t) {
    t2p <- twopi * t + init.angle * pi/180
    list(x = radius * cos(t2p), y = radius * sin(t2p), an=t2p)
}

然后,您可以指定参数 srttext调用,以度为单位,根据 x 有 2 个选项:
text(1.1 * P$x, 1.1 * P$y, labels[i], xpd = TRUE, 
     srt = ifelse(P$x < 0, P$an/pi*180+180, P$an/pi*180),
     adj = ifelse(P$x < 0, 1, 0), ...)

使用您的数据,调用修改后的 pie函数,你会得到下面的图:
enter image description here

关于r - 在 R 中向饼图添加标签...辐射 "spokes"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30885116/

相关文章:

css - 将 CSS 类添加到 Shiny 的 textOutput

r - 检测 R 中的操作系统(例如,对于自适应 .Rprofile 文件)

charts - 人力车-js图表库: Need strings instead of numbers on axes

javascript - 错误 : <g> attribute transform: Expected number, "translate(undefined,undefi…"

javascript - 为什么很难根据固定柱形图(highcharts)中的数据动态设置点填充和放置?

r - 在函数内创建文件夹

r - sendmailR : how to handle occasional “Unknown SMTP code” errors

r - 用 grid.arrange 排列的标签图

r - 如何使用 ggplot2 将标准误差线添加到箱须图?

r - 将堆栈和闪避与 ggplot2 中的条形图相结合