我一直在寻找在R中创建一个多级饼图(或圆环图),我发现最好的是sunburstR包,我必须说这是一个非常有前途的工具。
互动功能很棒 - 但我并不需要它。我想在图例对象中添加标题和计数,并将图形导出为图像格式。这需要高级HTML编码吗?关于这个包在网上没有太多的帮助材料。我应该查看差异包吗? pie()函数用于单级数据,我在此论坛上找到的ggplot2的geom_polar示例似乎不适合因素。
以下是我的数据集和sunburstR对象的示例 - 但是我的问题本质上更为通用,并不特定于此示例。
require(sunburstR)
data = gg=structure(list(V1 = structure(c(2L, 1L, 3L, 4L, 8L, 5L, 6L, 7L
), .Label = c("Pine Tree-Soft", "Pine Tree-Hard",
"Pine Tree-Long", "Pine Tree-Undecided", "Maple Tree-Red",
"Maple Tree-Green", "Maple Tree-Yellow",
"Maple Tree-Delicious"), class = "factor"), V2 = c(3L,
5L, 2L, 1L, 10L, 5L, 3L, 2L)), .Names = c("V1", "V2"), row.names = c(NA,
-8L), class = "data.frame")
sunburst(data)
任何帮助或建议将不胜感激。谢谢。
答案 0 :(得分:1)
我将添加一个示例以防您可能想要使用此选项,但似乎您希望避免额外的编码。 要求(sunburstR)
data = gg=structure(list(V1 = structure(c(2L, 1L, 3L, 4L, 8L, 5L, 6L, 7L
), .Label = c("Pine Tree-Soft", "Pine Tree-Hard",
"Pine Tree-Long", "Pine Tree-Undecided", "Maple Tree-Red",
"Maple Tree-Green", "Maple Tree-Yellow",
"Maple Tree-Delicious"), class = "factor"), V2 = c(3L,
5L, 2L, 1L, 10L, 5L, 3L, 2L)), .Names = c("V1", "V2"), row.names = c(NA,
-8L), class = "data.frame")
sb <- sunburst(
data,
count = TRUE, # add count just for demonstration
legend = list(w=250), # make extra room for our legend
legendOrder = unique(unlist(strsplit(as.character(data$V1),"-")))
)
# for the coding part
# to add some additional information in the legend,
# force show the legend,
# and disable toggling of the legend
htmlwidgets::onRender(
sb,
"
function(el,x) {
// force show the legend
// check legend
d3.select(el).select('.sunburst-togglelegend').property('checked',true);
// simulate click
d3.select(el).select('.sunburst-togglelegend').on('click')();
// change the text in the legend to add count
d3.select(el).selectAll('.sunburst-legend text')
.text(function(d) {return d.name + ' ' + d.value})
// remove the legend toggle
d3.select(el).select('.sunburst-togglelegend').remove()
}
"
)
答案 1 :(得分:0)
您可以使用ggsunburst包生成一个sunburst。 它基于ggplot2,因此您可以使用ggsave导出为图像。
这里有一个使用您的数据的示例。所有信息都可以包含在图中,因此我删除了图例
# install ggsunburst package
if (!require("ggplot2")) install.packages("ggplot2")
if (!require("rPython")) install.packages("rPython")
install.packages("http://genome.crg.es/~didac/ggsunburst/ggsunburst_0.0.9.tar.gz", repos=NULL, type="source")
library(ggsunburst)
df <- read.table(header = T, text = "
parent node size
Pine Hard 3
Pine Soft 5
Pine Long 2
Pine Undecided 1
Maple Delicious 10
Maple Red 5
Maple Green 3
Maple Yellow 2
")
write.table(df, 'df.csv', sep = ",", row.names = F)
sb <- sunburst_data('df.csv', type = "node_parent", sep = ",", node_attributes = "size")
p <- sunburst(sb, node_labels = T, leaf_labels = F, rects.fill.aes = "name") +
geom_text(data = sb$leaf_labels,
aes(x=x, y=y, label=paste(label, size, sep="\n"), angle=angle), size = 2) +
scale_fill_discrete(guide = F)
ggsave('sunburst.png', plot = p, w=4, h=4)