pok
pok

Reputation: 1

Adding a plot legend with geom_scatterpie_legend in R

I have prepared sample data. I am trying to add a legend on the scatterpie plot in R. My data looks something like this

> dat
     Y  X  A  B  C Total
1  100 10 11 49  3    63
2   80 10  2 28 26    56
3   60 10 11  0 13    24
4   40 10 19 32 26    77
5   20 10  4 48 14    66
6  100 20  0  0  0     0
7   80 20  0 10  0    10
8   60 20  0  0 20    20
9   40 20  6  0  0     6
10  20 20  0  0  0     0
11 100 30  5 11  5    21
12  80 30 15 27 15    57
13  60 30  4 42 16    62
14  40 30 15 12  6    33
15  20 30 20 22 17    59
16 100 40  3 33 19    55
17  80 40 16  0 28    44
18  60 40  9 40  9    58
19  40 40 12 25  4    41
20  20 40  5 42  7    54
21 100 50  2 21  1    24
22  80 50  6 26  7    39
23  60 50 16 29 10    55
24  40 50  0  0 11    11
25  20 50 20 10  0    30
26 100 60  3 13 27    43
27  80 60 16 40  3    59
28  60 60 17 14  7    38
29  40 60 19 10  9    38
30  20 60  3 16 11    30
31 100 70  4 40  3    47
32  80 70 18  2  6    26
33  60 70  0  0  0     0
34  40 70 17  8  9    34
35  20 70  6 28  2    36
36 100 80 18 13 10    41
37  80 80 11 17  3    31
38  60 80 10 28 30    68
39  40 80  4 13  2    19
40  20 80 17 19 15    51

and here's my code

library(ggplot2)
library(scatterpie)
dt = ggplot() + geom_scatterpie(data = dat, aes(x=X, y=Y, r=Total/20),
                           cols = c("A", "B", "C"),color=NA, alpha=.9)
dt <- dt + geom_scatterpie_legend(dat$Total, x=10, y=10)
dt <- dt + coord_equal()
dt

Now, I want to add a legend with scale, but the code produces:

Warning message: In FUN(X[[i]], ...) : NAs introduced by coercion to integer range

and

1: Removed 5 rows containing non-finite values (stat_arc_bar).
2: Removed 5 rows containing missing values (geom_segment).
3: Removed 5 rows containing missing values (geom_text).

What's the right way to do it? Thank you for the hlep.

Scatterpie plot image

Upvotes: 0

Views: 1428

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174516

The first argument to geom_scatterpie_legend should be just a vector of the actual radius sizes you wish to show. It is up to you to rescale these to represent your data. For example, since you are scaling to 1/20 of column Total, you can create a sequence from 1 to the maximum value of Total/20. However, you need a labeller function to translate these back to the same scale as Total:

library(ggplot2)
library(scatterpie)

ggplot() + 
  geom_scatterpie(data = dat, aes(x = X, y = Y, r = Total / 20),
                  cols = c("A", "B", "C"), color = NA, alpha = 0.9) +
  geom_scatterpie_legend(seq(1, ceiling(max(dat$Total) / 20), length = 4), 
                         x = 10, y = 10, labeller = function(x) x * 20) +
  coord_equal()

enter image description here

Upvotes: 1

Related Questions