[R] plot categorical variable with percentage infomation

jim holtman jholtman at gmail.com
Mon Aug 26 19:04:51 CEST 2013


Here is a way of getting the percents (and total if you want it):

a=as.factor(sample(1:3,10,replace=T))
# use 'barplot' since it return x-values for putting labels on bars
aTable <- table(a)  # count the factors
xPos <- barplot(aTable)
# put percent at top bar
text(xPos, aTable, sprintf("%.0f%%", aTable * 100 / sum(aTable)), xpd = TRUE)




Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.


On Mon, Aug 26, 2013 at 12:43 PM, Adams, Jean <jvadams at usgs.gov> wrote:
> Jie,
>
> I'm not exactly sure what you're after.  Perhaps this will help you get
> started.
>
> count <- table(a)
> prop <- count/length(a)
> b <- plot(a)
> text(b, count, prop, pos=1)
>
> Jean
>
>
> On Mon, Aug 26, 2013 at 11:27 AM, Jie <jimmycloud at gmail.com> wrote:
>
>> Dear All,
>>
>> Suppose I have a categorical variable
>> a=as.factor(sample(1:3,10,replace=T))
>>
>> plot(a) and hist(as.numeric(a),freq=F) would give the histogram of it.
>> But I do not know how to add the counts or percentage information for
>> plot.factor().
>> hist() can do it but as a numeric variable, the x-axis is not 3
>> categories in this case.
>> Thank you for any suggestion.
>>
>> Best wishes,
>> Jie
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> 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.
>>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.



More information about the R-help mailing list