[R] how to add count to pie chart legend

John Fox j|ox @end|ng |rom mcm@@ter@c@
Tue Aug 16 13:36:21 CEST 2022


Dear Jim and Ana,

Why not skip the legend and put the counts in the labels?

with(df, pie(n, paste0(V1, " (", n, ")"),
     col=c(3, 2), main="Yes and No", radius=1))

Best,
  John

On 2022-08-15 9:43 p.m., Jim Lemon wrote:
> Hi Ana,
> A lot of work for a little pie.
> 
> df<-read.table(text="V1 n
>   Yes 8
>   No 14",
>   header=TRUE,
>   stringsAsFactors=FALSE)
> par(mar=c(5,4,4,4))
> pie(df$n,df$V1,col=c(3,2),main="Yes and No",
>   xlab="",ylab="",radius=1)
> legend(0.75,-0.8,paste(df$V1,df$n),fill=c(3,2),
>   xpd=TRUE)
> 
> Jim
> 
> On Tue, Aug 16, 2022 at 1:59 AM Ana Marija <sokovic.anamarija using gmail.com> wrote:
>>
>> Hi All,
>>
>> I have df like this:
>>
>>> df# A tibble: 2 × 4
>>    V1        n  perc labels
>>    <chr> <int> <dbl> <chr> 1 Yes       8 0.364 36%   2 No       14 0.636 64%
>>
>> I am making pie chart like this:
>>
>> library(ggplot2)
>>
>> ggplot(df, aes(x = "", y = perc, fill = V1)) +
>>    geom_col(color = "black") +
>>    geom_label(aes(label = labels),
>>               position = position_stack(vjust = 0.5),
>>               show.legend = FALSE) +
>>    guides(fill = guide_legend(title = "Answer")) +
>>    coord_polar(theta = "y") +
>>    theme_void()
>>
>> How would I add in the legend beside Answer "Yes" count 8 (just number
>> 8) and beside "No" count 14?
>>
>> Thanks
>>
>> Ana
>>
>>          [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
-- 
John Fox, Professor Emeritus
McMaster University
Hamilton, Ontario, Canada
web: https://socialsciences.mcmaster.ca/jfox/



More information about the R-help mailing list