Pie chart based on table in R

Yasmin

I would like to plot one piechart to represent 4 people, each has different values for 3 categories.

Name           X            Y                Z
Bill          120         280               600
John          140         360               500 
Johana        150         700               150
Tim           200         600               200

What I want to do is to have one pie-chart which is split into 4 equal areas (Bill,John, Johana, Tim), and per each area, it's split according to the values of X, Y, Z. I tried to plot values in R based on table, but unfortunately it does not work. Can anyone give me a guidance how this can be done in R ?

Barranka

You need to reshape a bit your data to fit your needs. Use the reshape package to create a "melted" data frame:

df <- data.frame(
  name=c('Bill','John','Johana','Tim'),
  x = c(120,140,150,200),
  y = c(280,360,700,600),
  z = c(600,500,150,200)
)

library(reshape)
df2 <- sort_df(
         melt(df, id='name')
         , vars=c('name','variable')
       )
pie(df2$value) # ONLY take the value column to create the chart.

I leave to you define the slices colors and labels.


The explanation:

The melt() function will "unpivot" your dataframe. The result will be something like this:

library(reshape)
melt(df, id='name')
     name variable value
1    Bill        x   120
2    John        x   140
3  Johana        x   150
4     Tim        x   200
5    Bill        y   280
6    John        y   360
7  Johana        y   700
8     Tim        y   600
9    Bill        z   600
10   John        z   500
11 Johana        z   150
12    Tim        z   200

The sort_df() function will simply sort the entries by name and variable:

sort_df(melt(df, id='name'), vars=c('name','variable'))
     name variable value
1    Bill        x   120
5    Bill        y   280
9    Bill        z   600
3  Johana        x   150
7  Johana        y   700
11 Johana        z   150
2    John        x   140
6    John        y   360
10   John        z   500
4     Tim        x   200
8     Tim        y   600
12    Tim        z   200

All that's left is plot the pie. As the sum of the values per name is 1000 for all the names, you'll not need to rescale the values. I leave to you how to rescale the values if the sum for each name is different.


References:

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related