我想在ggplot中制作饼图
我的数据:
lab <- c("a", "b", "c", "d", "e", "f", "g", "h")
percentage <- c(50, 20, 10, 10, 2, 2,2,2)
df.prison <- data.frame(lab, percentage)
df.prison$crime <- factor(df.prison$lab, levels=rev(levels(df.prison$lab)))
labels.prison <- paste(lab, "-", percentage, "%", sep="")
简介:
plot <- ggplot(data=df.prison, aes(x=factor(1), y=percentage, fill=factor(lab))) +
geom_bar(width=1, stat="identity") +
coord_polar(theta="y") +
ylab("") +
xlab("") +
labs(fill="") +
theme(axis.ticks = element_blank(), panel.grid = element_blank(), axis.text = element_blank()) +
geom_text(aes(y = percentage/2 + c(0, cumsum(percentage)[-length(percentage)]), label=labels.prison))
plot
我对这个情节有两个问题: 我不想拥有传奇(因为标签非常短(一个字母),我想把它们放在饼图上 2.是否可以在图块旁边放置小块(小于几个百分比)的标签,因为标签太大而不能放在这个小块内。例如,像这里:
http://www.conceptdraw.com/How-To-Guide/picture/Pie-chart-Sector-weightings.png
感谢您的任何建议:)
答案 0 :(得分:3)
legend.position = 'none'
将删除图例。您可以通过x
的映射调整geom_text
值来调整标签。
library(ggplot2)
lab <- c("a", "b", "c", "d", "e", "f", "g", "h")
percentage <- c(50, 20, 10, 10, 2, 2, 2, 2)
df.prison <- data.frame(lab, percentage)
df.prison$crime <- factor(df.prison$lab, levels=rev(levels(df.prison$lab)))
labels.prison <- paste(lab, "-", percentage, "%", sep="")
ggplot(data=df.prison, aes(x=factor(1), y=percentage, fill=factor(lab))) +
geom_bar(width=1, stat="identity") +
coord_polar(theta="y") +
ylab("") +
xlab("") +
labs(fill="") +
theme(legend.position = "none", ### Solution to part 1, no legend
axis.ticks = element_blank(),
panel.grid = element_blank(),
axis.text = element_blank()) +
geom_text(aes(x = c(1, 1, 1, 1, 1.2, 1.3, 1.4, 1.5), # Solution for part 2,
y = percentage / 2 + c(0, cumsum(percentage)[-length(percentage)]),
label=labels.prison))