我有这样的数据,我需要绘制饼图:
final envVars = Platform.environment;
final bin = envVars['GOOGLE_CHROME_SHIM'];
final driver = await createDriver(binary: Uri.parse(bin), desired: Capabilities.chrome);
现在,我还要在图表外的相应切片处添加百分比。因此,我的英文幻灯片的圆周将有# Creat bar chart for jam language
library("ggplot2") # Data visualization
library("dplyr") # Data manipulation
library("RColorBrewer")
myPalette <- brewer.pal(5, "Set2")
all_languages <- data.frame(
Languages = c("English", "French", "Spanish", "Portuguese", "Others"),
n = c(81, 4, 3, 2, 3),
prop = c(87.1, 4.3, 3.2, 2.2, 3.2)
)
# Add label position
all_languages <-all_languages %>%
arrange(desc(Languages)) %>%
mutate(lab.ypos = cumsum(n) - 0.5*n)
ggplot(all_languages , aes(x = "", y = n, fill = Languages)) +
geom_bar(width = 1, stat = "identity", color = "white") +
coord_polar("y", start = 0)+
geom_text(aes(y = lab.ypos, label = n), color = "white")+
scale_fill_manual(values = myPalette) +
theme_void()
。我的百分比存储在87.1%
中。我该怎么做?
其次,我如何将标签移离中心一点点?这是因为在较小的切片中,数字标签太杂乱了。
尝试:我确实尝试遵循此答案How can I put the labels outside of piechart?
但是它抛出一个错误,提示缺少两行...特别是,我的西班牙语和葡萄牙语切片没有标签。另外,我的情况也有所不同,因为我要同时在标签内和外面都加标签。
我尝试使用以下代码遵循该答案:
all_languages$prop
我收到以下警告
警告消息:删除了包含缺失值(geom_text)的2行
最终决定:我将按照下面Bappa Das的回答进行操作,并稍微修改标签。我会将计数和百分比都放在饼图之外。
答案 0 :(得分:1)
您可以将以下代码与基数R一起使用
library(RColorBrewer)
Languages = c("English", "French", "Spanish", "Portuguese", "Others")
n = c(81, 4, 3, 2, 3)
prop = c("87.1", "4.3", "3.2", "2.2", "3.2")
lbls <- paste(prop,"%",sep=" ")
lgd <- c("English", "French", "Spanish", "Portuguese", "Others")
cols = brewer.pal(n = length(prop), name = 'Set3')
pie(n, labels = lbls, col=cols)
legend("topright", legend=lgd, cex=0.9, bty = "n", fill = cols)
这是您想要的吗?