牛眼图
我的同事需要绘制101个牛眼图。这不是她的想法。我没有在Excel中让她的奴隶离开,或者上帝知道是什么制造这些东西,我愿意在R中做它们;将条形图绘制为极坐标以制作牛眼在ggplot2
中变得轻而易举。牛眼图
但是我遇到了一个问题:数据已经汇总了,所以Hadley的例子here对我不起作用。我可以将计数扩展为一个因素来做到这一点,但我觉得有一个更好的方法 - 告诉geom_bar如何读取数据的一种方法。
的数据是这样的:
Zoo Animals Bears Polar Bears
1 Omaha 50 10 3
我会作出对每个动物园的情节 - 不过这部分,我可以管理。
,这里是它的dput
:
structure(list(Zoo = "Omaha", Animals = "50", Bears = "10", `Polar Bears` = "3"), .Names = c("Zoo",
"Animals", "Bears", "Polar Bears"), row.names = c(NA, -1L), class = "data.frame")
注:这是显著动物> =熊> =北极熊。此外,她不在城里,所以我不能从她那里得到原始数据(无论如何,如果有一个大文件的话)。
这样做没有分列的方式是在geom_bar
使用stat="identity"
。
它有助于有包含数字值,而不是字符串数据帧开始:
dat <- data.frame(Zoo = "Omaha",
Animals = 50, Bears = 10, `Polar Bears` = 3)
我们确实需要reshape2::melt
得到适当的组织数据:
library(reshape2)
d3 <- melt(dat,id.var=1)
现在创建情节(等同于其他的答案):
library(ggplot2)
ggplot(d3, aes(x = variable, y = value)) +
geom_bar(width = 1, colour = "black",stat="identity") +
coord_polar()
当我们在等待更好的答案时,我想我应该发布你提到的(次优)解决方案。 dat
是包含在您的问题中的结构。
d <- data.frame(animal=factor(sapply(list(dat[2:length(dat)]),
function(x) rep(names(x),x))))
cxc <- ggplot(d, aes(x = animal)) + geom_bar(width = 1, colour = "black")
cxc + coord_polar()
谢谢,克里斯!这非常接近我放在一起的东西,除了我已经明确说明了每个组的rep()。 sapply()对我来说仍然很神奇。 – 2009-09-11 19:31:24
您可以使用inverse.rle
重新创建数据,
dd = list(lengths = unlist(dat[-1]), values = names(dat)[-1])
class(dd) = "rle"
inverse.rle(dd)
如果你有多个动物园(行),你可以尝试
l = plyr::dlply(dat, "Zoo", function(z)
structure(list(lengths = unlist(z[-1]), values = names(z)[-1]), class = "rle"))
reshape2::melt(llply(l, inverse.rle))
这是一些非常聪明的数据纠缠 - +1 – 2012-12-26 18:47:52
这对我来说似乎是最直观的答案 - 我最近经常在我的工作中做这类事,尽管当时我很难记得我是否理解了熔化数据的概念。感谢您花时间回答这个老问题! – 2012-12-26 18:54:27