在R中向饼图添加标签...辐射“辐射"? [英] Adding labels to pie chart in R... Radiating "spokes"?

查看:64
本文介绍了在R中向饼图添加标签...辐射“辐射"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法(可能使用ggplot或其他软件包)在R中倾斜饼图的标签?例如,此代码(使用R默认值):

Is there a way (using ggplot or some other package maybe) to angle the labels of a pie chart in R? For example, this code (using R defaults):

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

创建此饼图:

我想要的是一个这样的饼图(我在PhotoShop中非常粗略地创建了它):

What I want is a pie chart like this (which I created very roughly in PhotoShop):

推荐答案

正如@agstudy指出的那样,您需要修改函数主体以创建自己的 pie 函数.实际上, pie 不会返回任何值,因此您不知道将标签确切放置在何处以及以哪个角度放置.

As @agstudy pointed out, you need to modify the body of the function to create your own pie function. Indeed, pie does not return any value so you don't know where exactly to put your labels and with which angle.

首先,您可以使用 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一样).为了使用正确的角度,您必须对其进行计算(这是我的答案与其他答案变得不同的部分...).实际上,它已经在绘图之前通过以下方式进行了计算:

The part that is interesting to you is what follows text, where you can specify an angle to rotate them (like @agstudy did). In order to use the correct angle, you've got to compute it (this is the part where my answer becomes different from the other one...). Actually, it is already computed right before the drawing, with:

t2xy <- function(t) {
    t2p <- twopi * t + init.angle * pi/180
    list(x = radius * cos(t2p), y = radius * sin(t2p))
}

您只需要使此功能还输出角度:

you just need to make this function also output the angle:

t2xy <- function(t) {
    t2p <- twopi * t + init.angle * pi/180
    list(x = radius * cos(t2p), y = radius * sin(t2p), an=t2p)
}

然后,您可以在 text 调用中指定参数 srt ,以度为单位放置角度,并根据x设置2个选项:

Then, you can specify the parameter srt in the text call, putting the angle in degrees, with 2 options according to x:

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 函数,您将获得以下图表:

With your data, calling the modified pie function, you'll get the below plot:

这篇关于在R中向饼图添加标签...辐射“辐射"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆