本文介绍了R + ggplot2 =&gt;在facet饼图上添加标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想在face face馅饼char上添加数据标签。 也许有人可以帮助我。 我的数据: year prod rm(year,prod,quantity) 代码: library(ggplot2) #手工计算的中心 centr2 ggplot(data = df,aes(x = factor(1),y = quantity,fill = factor(prod)))+ geom_bar(stat =identity)+ geom_text(aes(x = factor(1),y = centr2,label = df $ quantity),size = 10)+ facet_grid(facets =。〜 year,labeller = label_value)+ coord_polar(theta =y) 结果是: 如果我删除coord_polar(theta =y),我会得到f以下情节: 现在很明显,为什么我的数据标签不匹配。 但我不知道如何解决它。 我阅读: 1. 在饼图上放置标签 2. 将文本添加到ggplot中,使用分面密度 3. >彼得的情节获取其文本之间的对方 但没有找到答案。 解决方案我会通过定义另一个变量(我称之为 pos )在 df 中计算文本标签的位置。我用 dplyr 来做到这一点,当然也可以使用其他方法。 library(dplyr) library(ggplot2) df< - df%>%group_by(year)%>%mutate(pos = cumsum(quantity) - quantity / 2) ggplot(data = df,aes(x = factor(1),y = quantity,fill = factor(prod)))+ geom_bar(stat =identity)) + geom_text(aes(x = factor(1),y = pos,label = quantity),size = 10)+#note y = pos facet_grid(facets =。〜year,labeller = label_value )+ coord_polar(theta =y) I want to add data labels on faceted pie char.Maybe someone can can help me.My data: year <- c(1,2,1,2,1,2)prod <- c(1,1,2,2,3,3)quantity <- c(33,50,33,25,34,25)df <- data.frame(year, prod, quantity)rm(year, prod, quantity)Code:library(ggplot2)# center's calculated by handcentr2 <- c(16, 25, 49, 62.5, 81, 87.5)ggplot(data=df, aes(x=factor(1), y=quantity, fill=factor(prod))) + geom_bar(stat="identity") + geom_text(aes(x= factor(1), y=centr2, label = df$quantity), size=10) + facet_grid(facets = .~year, labeller = label_value) + coord_polar(theta = "y")And my result is:If I remove coord_polar(theta = "y"), I will have the following plot:And now it is clear for me, why my data labels did not match.But I don't know how to fix it.I read:1. Place labels on Pie Chart2. Add text to ggplot with facetted densities3. Pie plot getting its text on top of each otherBut didn't find the answer. 解决方案 I would approach this by defining another variable (which I call pos) in df that calculates the position of text labels. I do this with dplyr but you could also use other methods of course.library(dplyr)library(ggplot2)df <- df %>% group_by(year) %>% mutate(pos = cumsum(quantity)- quantity/2)ggplot(data=df, aes(x=factor(1), y=quantity, fill=factor(prod))) + geom_bar(stat="identity") + geom_text(aes(x= factor(1), y=pos, label = quantity), size=10) + # note y = pos facet_grid(facets = .~year, labeller = label_value) + coord_polar(theta = "y") 这篇关于R + ggplot2 =&gt;在facet饼图上添加标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-29 03:52
查看更多