-
Notifications
You must be signed in to change notification settings - Fork 4
/
04-part.Rmd
2361 lines (1803 loc) · 90.6 KB
/
04-part.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Part of a Whole {#part}
---
```{r small-multiple-group-part-intro-image, echo=FALSE, fig.align='center', fig.cap="Barchart Small Multiple", out.width = '75%'}
knitr::include_graphics("https://www.r-graph-gallery.com/48-grouped-barplot-with-ggplot2_files/figure-html/thecode5-1.png")
```
## Circular Packing
---
[Circular packing](https://www.data-to-viz.com/graph/circularpacking.html) or [circular treemap](https://www.data-to-viz.com/graph/circularpacking.html) allows to visualize a <u>hierarchic organization</u>. It is an equivalent of a [treemap](https://www.r-graph-gallery.com/treemap.html) or a [dendrogram](https://www.r-graph-gallery.com/dendrogram.html), where each node of the tree is represented as a circle and its sub-nodes are represented as circles inside of it.
#### One Level - `packcircles` and `ggplot2`
If your dataset has no hierarchy (it is basically just a few entities with attributed numeric values), the `packcircles` package is the best way to build a circular packing chart in R. The packages basically computes the position of each bubble, allowing to build the chart with `ggplot2`.
### Basic Circle Packing with One Level
This page aims to describe how to build a basic [circle packing](https://www.r-graph-gallery.com/circle-packing.html) chart with only one level of hierarchy. It uses the `packcircle` package for circle position, and `ggplot2` for drawing. This page aims to describe how to build a basic circle packing chart with only one level of hierarchy. Basically, you just represent each entity or individual of your dataset with a circle, its size depending on a provided value.
It is like a [barplot](https://www.r-graph-gallery.com/barplot.htmlv), but you use circle size instead of bar length. It is close to a [bubble plot](https://www.r-graph-gallery.com/bubble-chart.html), but X and Y positions do not mean anything. It is a circle version of a [treemap](https://www.r-graph-gallery.com/treemap.html).
Calculating the arrangement of dots is not a trivial problem. The `packcircles` library solves it and output coordinates of every points of the circle edges.
Finally, ggplot2 allows to draw shapes thanks to `geom_polygon()`.
```r
# Libraries
library(packcircles)
library(ggplot2)
# Create data
data <- data.frame(group=paste("Group", letters[1:20]), value=sample(seq(1,100),20))
# Generate the layout. This function return a dataframe with one line per bubble.
# It gives its center (x and y) and its radius, proportional of the value
packing <- circleProgressiveLayout(data$value, sizetype='area')
# We can add these packing information to the initial data frame
data <- cbind(data, packing)
# Check that radius is proportional to value. We don't want a linear relationship, since it is the AREA that must be proportionnal to the value
# plot(data$radius, data$value)
# The next step is to go from one center + a radius to the coordinates of a circle that
# is drawn by a multitude of straight lines.
dat.gg <- circleLayoutVertices(packing, npoints=50)
# Make the plot
ggplot() +
# Make the bubbles
geom_polygon(data = dat.gg, aes(x, y, group = id, fill=as.factor(id)), colour = "black", alpha = 0.6) +
# Add text in the center of each bubble + control its size
geom_text(data = data, aes(x, y, size=value, label = group)) +
scale_size_continuous(range = c(1,4)) +
# General theme:
theme_void() +
theme(legend.position="none") +
coord_equal()
```
<center>
![](https://www.r-graph-gallery.com/305-basic-circle-packing-with-one-level_files/figure-html/thecode-1.png){width=75%}
</center>
### Circle Packing Customization with R
This page is dedicated to one level [circle packing](https://www.r-graph-gallery.com/circle-packing.html) customization with R. It notably shows how to use different color palettes and provides reproducible code snippets.
#### Using the `Viridis` Color Scale
This chart follows the previous most [basic circle packing](https://www.r-graph-gallery.com/305-basic-circle-packing-with-one-level) section.
It shows how to use the awesome `viridis` package to build color scales, a very good alternative to the usual `colorBrewer`.
Note that `magma` is used here, but you could use the same code with `inferno` or `viridis` instead.
```r
# libraries
library(packcircles)
library(ggplot2)
library(viridis)
# Create data
data <- data.frame(group=paste("Group", letters[1:20]), value=sample(seq(1,100),20))
# Generate the layout. sizetype can be area or radius, following your preference on what to be proportional to value.
packing <- circleProgressiveLayout(data$value, sizetype='area')
data <- cbind(data, packing)
dat.gg <- circleLayoutVertices(packing, npoints=50)
# Basic color customization
ggplot() +
geom_polygon(data = dat.gg, aes(x, y, group = id, fill=as.factor(id)), colour = "black", alpha = 0.6) +
scale_fill_manual(values = magma(nrow(data))) +
geom_text(data = data, aes(x, y, size=value, label = group)) +
scale_size_continuous(range = c(1,4)) +
theme_void() +
theme(legend.position="none") +
coord_equal()
```
<center>
![](https://www.r-graph-gallery.com/306-custom-circle-packing-with-one-level_files/figure-html/thecode-1.png){width=75%}
</center>
### Map Color to Bubble Value
It is a common task to make the bubble color being lighter or darker according to its value.
This is possible by passing the focus variable to the dataframe that is read by `ggplot2`, and specifying it in tha `aes()`.
```r
# First I need to add the 'value' of each group to dat.gg.
# Here I repeat each value 51 times since I create my polygons with 50 lines
dat.gg$value <- rep(data$value, each=51)
# Plot
ggplot() +
# Make the bubbles
geom_polygon(data = dat.gg, aes(x, y, group = id, fill=value), colour = "black", alpha = 0.6) +
scale_fill_distiller(palette = "BuPu", direction = 1 ) +
# Add text in the center of each bubble + control its size
geom_text(data = data, aes(x, y, size=value, label = group)) +
scale_size_continuous(range = c(1,4)) +
# General theme:
theme_void() +
theme(legend.position="none") +
coord_equal()
```
<center>
![](https://www.r-graph-gallery.com/306-custom-circle-packing-with-one-level_files/figure-html/thecode2-1.png){width=75%}
</center>
### Background Customization
Change the background thanks to the `theme()` function and its `plot.background()` argument.
```r
ggplot() +
# Make the bubbles
geom_polygon(data = dat.gg, aes(x, y, group = id, fill=value), colour = "grey", alpha = 0.6, size=.5) +
scale_fill_distiller(palette = "Spectral", direction = 1 ) +
# Add text in the center of each bubble + control its size
geom_label(data = data, aes(x, y, size=value, label = group)) +
scale_size_continuous(range = c(1,4)) +
# General theme:
theme_void() +
theme(
legend.position="none",
plot.background = element_rect(fill="black"),
plot.title = element_text(color="white")
) +
coord_equal() +
ggtitle("A custom circle packing with\nblack background")
```
<center>
![](https://www.r-graph-gallery.com/306-custom-circle-packing-with-one-level_files/figure-html/thecode3-1.png){width=75%}
</center>
### Space between Bubbles
This chart is just a customization of the [chart #305](https://www.r-graph-gallery.com/305-basic-circle-packing-with-one-level.html) which describes the basic process to make a one level circle packing chart. I personally like to add a bit of space between each circle.
Basically, all you have to do is to reduce the `radius` size in your data once this one has been calculated. Just multiply it by a number under 0, and it will decrease the circle size.
If you have been so far, you probably want to check the [interactive version](https://www.r-graph-gallery.com/308-interactive-circle-packing.html) of the chart !
```r
# libraries
library(packcircles)
library(ggplot2)
library(viridis)
# Create data
data <- data.frame(group=paste("Group", letters[1:20]), value=sample(seq(1,100),20))
# Generate the layout
packing <- circleProgressiveLayout(data$value, sizetype='area')
packing$radius <- 0.95*packing$radius
data <- cbind(data, packing)
dat.gg <- circleLayoutVertices(packing, npoints=50)
# Plot
ggplot() +
geom_polygon(data = dat.gg, aes(x, y, group = id, fill=id), colour = "black", alpha = 0.6) +
scale_fill_viridis() +
geom_text(data = data, aes(x, y, size=value, label = group), color="black") +
theme_void() +
theme(legend.position="none")+
coord_equal()
```
<center>
![](https://www.r-graph-gallery.com/307-add-space-in-circle-packing_files/figure-html/thecode-1.png){width=75%}
</center>
### Interactive Circle Packing with R
This section describes how to build an interactive [circle packing](https://www.r-graph-gallery.com/circle-packing.html) chart with R and the `ggiraph` package. It allows to hover bubbles to get additionnal information.
This chart follows sections [#305](https://www.r-graph-gallery.com/305-basic-circle-packing-with-one-level.html) and [#306](https://www.r-graph-gallery.com/306-custom-circle-packing-with-one-level.html) that explains how to build a static version of circle packing, and how to customize it.
This interactive version is very close to the static one. It uses the `ggiraph` library to transform the `ggplot2` code in something interactive. The steps are quite easy:
* First you need to prepare a column in the data frame with the text you want to display while hovering.
* Second, you need to change the geometries to use the interactive geometries of ggiraph.
Check the code below:
```r
# libraries
library(packcircles)
library(ggplot2)
library(viridis)
library(ggiraph)
# Create data
data <- data.frame(group=paste("Group_", sample(letters, 70, replace=T), #sample(letters, 70, replace=T), sample(letters, 70, replace=T), sep="" ), #value=sample(seq(1,70),70))
# Add a column with the text you want to display for each bubble:
data$text <- paste("name: ",data$group, "\n", "value:", data$value, "\n", "You can add a story here!")
# Generate the layout
packing <- circleProgressiveLayout(data$value, sizetype='area')
data <- cbind(data, packing)
dat.gg <- circleLayoutVertices(packing, npoints=50)
# Make the plot with a few differences compared to the static version:
p <- ggplot() +
geom_polygon_interactive(data = dat.gg, aes(x, y, group = id, fill=id, #tooltip = data$text[id], data_id = id), colour = "black", alpha = 0.6) +
scale_fill_viridis() +
geom_text(data = data, aes(x, y, label = gsub("Group_", "", group)), #size=2, color="black") +
theme_void() +
theme(legend.position="none", plot.margin=unit(c(0,0,0,0),"cm") ) +
coord_equal()
# Turn it interactive
widg <- ggiraph(ggobj = p, width_svg = 7, height_svg = 7)
widg
# save the widget
library(htmlwidgets)
saveWidget(widg, file=paste0( getwd(), "/HtmlWidget/circular_packing_interactive.html"))
```
<center>
```{r circular-packing-interactive, echo=FALSE}
htmltools::tags$iframe(title = "My embedded document", src = "partHtml/circular_packing_interactive.html", height="400px", width = "100%")
```
</center>
### Basic Circle Packing with Several Hierarchy Level
This page is dedicated to multi level circle packing. It explains how to build one using R and the ggraph package.
#### Several Levels - `ggraph`
If your dataset is a hierarchy, it is time to switch to other tools. For static versions, the `ggraph` package is the best option. It follows the grammar of graphic and makes it a breeze to customize the appearance following the same logic than `ggplot2`.
### Input & Concept
[Circular packing](https://www.r-graph-gallery.com/circular-packing.html) represents a hierarchy: The biggest circle (origin of the hierarchy) contains several big circles (nodes of level 1), which contain smaller circle (level 2) and so on.. The last level is called leaf.
The input data is a list of edges between nodes. It should look more or less like the table beside. Moreover, we usually accompany this table with another one that gives features for each node.
<center>
![*Edge List*](https://www.r-graph-gallery.com/img/other/Hierarchical_network_2col.png){width=25%}
</center>
#### Most Basic Circular Packing with `ggraph`
The `ggraph` package makes it a breeze to build a circular packing from an edge list. Here is an example based on the `flare` dataset proovded with the package.
The first step is to transform the dataframe to a graph object thanks to the `graph_from_data_frame()` function of the `igraph` package. Then, `ggraph` offers the `geom_node_circle()` function that will build the chart.
```r
# Libraries
library(ggraph)
library(igraph)
library(tidyverse)
# We need a data frame giving a hierarchical structure. Let's consider the flare dataset:
edges <- flare$edges
# Usually we associate another dataset that give information about each node of the dataset:
vertices <- flare$vertices
# Then we have to make a 'graph' object using the igraph library:
mygraph <- graph_from_data_frame( edges, vertices=vertices )
# Make the plot
ggraph(mygraph, layout = 'circlepack') +
geom_node_circle() +
theme_void()
```
<center>
![](https://www.r-graph-gallery.com/313-basic-circle-packing-with-several-levels_files/figure-html/thecode2-1.png){width=75%}
</center>
### Switching to another Chart Type
Note that the `ggraph` library allows to easily go from one type of representation to another. Indeed several types of representation are suitable for hierarchical data: [dendrogram](https://www.r-graph-gallery.com/dendrogram.html) (can be circular), [treemap](https://www.r-graph-gallery.com/treemap.html), sunburst diagram or [network](https://www.r-graph-gallery.com/network.html)!
```r
library(ggraph)
ggraph(mygraph, layout='dendrogram', circular=TRUE) +
geom_edge_diagonal() +
theme_void() +
theme(legend.position="none")
```
<center>
![](https://www.r-graph-gallery.com/313-basic-circle-packing-with-several-levels_files/figure-html/thecode3a-1.png){width=75%}
</center>
```r
ggraph(mygraph, layout='dendrogram', circular=FALSE) +
geom_edge_diagonal() +
theme_void() +
theme(legend.position="none")
```
<center>
![](https://www.r-graph-gallery.com/313-basic-circle-packing-with-several-levels_files/figure-html/thecode3b-1.png){width=75%}
</center>
```r
ggraph(mygraph, 'treemap', weight = size) +
geom_node_tile(aes(fill = depth), size = 0.25) +
theme_void() +
theme(legend.position="none")
```
<center>
![](https://www.r-graph-gallery.com/313-basic-circle-packing-with-several-levels_files/figure-html/thecode3c-1.png){width=75%}
</center>
```r
ggraph(mygraph, 'partition', circular = TRUE) +
geom_node_arc_bar(aes(fill = depth), size = 0.25) +
theme_void() +
theme(legend.position="none")
```
<center>
![](https://www.r-graph-gallery.com/313-basic-circle-packing-with-several-levels_files/figure-html/thecode3d-1.png){width=75%}
</center>
```r
ggraph(mygraph) +
geom_edge_link() +
geom_node_point() +
theme_void() +
theme(legend.position="none")
```
<center>
![](https://www.r-graph-gallery.com/313-basic-circle-packing-with-several-levels_files/figure-html/thecode3e-1.png){width=75%}
</center>
### Customized Circle Packing with R and ggraph
This page follows the previous [introduction](https://www.r-graph-gallery.com/313-basic-circle-packing-with-several-levels.html) that explained the basis of circle packing with R and the ggraph library. It describes how to customize color, size, labels and more.
#### Bubble Size Proportionnal to a Variable
Mapping the bubble size to a numeric variable allows to add an additionnal layer of information to the chart.
Here, the `vertices` data frame has a `size` column that is used for the bubble size. Basically, it just needs to be passed to the `weight` argument of the `ggraph()` function.
```r
# Libraries
library(ggraph)
library(igraph)
library(tidyverse)
library(viridis)
# We need a data frame giving a hierarchical structure. Let's consider the flare dataset:
edges <- flare$edges
vertices <- flare$vertices
mygraph <- graph_from_data_frame(edges, vertices=vertices)
# Control the size of each circle: (use the size column of the vertices data frame)
ggraph(mygraph, layout = 'circlepack', weight=size) +
geom_node_circle() +
theme_void()
```
<center>
![](https://www.r-graph-gallery.com/314-custom-circle-packing-with-several-levels_files/figure-html/thecode2-1.png){width=75%}
</center>
### Map Color to Hierarchy Depth
Adding color to circular packing definitely makes sense. The first option is to map color to depth: the origin of every node will have a color, the level 1 another one, and so on..
As usual, you can play with the colour palette to fit your needs. Here are 2 examples with the `viridis` and the `RColorBrewer` palettes:
```r
# Left: color depends of depth
p <- ggraph(mygraph, layout = 'circlepack', weight=size) +
geom_node_circle(aes(fill = depth)) +
theme_void() +
theme(legend.position="FALSE")
p
```
<center>
![](https://www.r-graph-gallery.com/314-custom-circle-packing-with-several-levels_files/figure-html/thecode3a-1.png){width=75%}
</center>
```r
# Adjust color palette: viridis
p + scale_fill_viridis()
```
<center>
![](https://www.r-graph-gallery.com/314-custom-circle-packing-with-several-levels_files/figure-html/thecode3b-1.png){width=75%}
</center>
```r
# Adjust color palette: colorBrewer
p + scale_fill_distiller(palette = "RdPu")
```
<center>
![](https://www.r-graph-gallery.com/314-custom-circle-packing-with-several-levels_files/figure-html/thecode3c-1.png){width=75%}
</center>
### Map Color to Hierarchy Depth
To add more insight to the plot, we often need to add labels to the circles. However you can do it only if the number of circle is not to big. Note that you can use `geom_node_text` (left) or `geom_node_label` to annotate leaves of the circle packing:
```r
# Create a subset of the dataset (I remove 1 level)
edges <- flare$edges %>%
filter(to %in% from) %>%
droplevels()
vertices <- flare$vertices %>%
filter(name %in% c(edges$from, edges$to)) %>%
droplevels()
vertices$size <- runif(nrow(vertices))
# Rebuild the graph object
mygraph <- graph_from_data_frame( edges, vertices=vertices )
```
<center>
![](https://www.r-graph-gallery.com/314-custom-circle-packing-with-several-levels_files/figure-html/thecode4a-1.png){width=75%}
</center>
```r
# left
ggraph(mygraph, layout = 'circlepack', weight=size ) +
geom_node_circle(aes(fill = depth)) +
geom_node_text( aes(label=shortName, filter=leaf, fill=depth, size=size)) +
theme_void() +
theme(legend.position="FALSE") +
scale_fill_viridis()
# Right
ggraph(mygraph, layout = 'circlepack', weight=size ) +
geom_node_circle(aes(fill = depth)) +
geom_node_label( aes(label=shortName, filter=leaf, size=size)) +
theme_void() +
theme(legend.position="FALSE") +
scale_fill_viridis()
```
<center>
![](https://www.r-graph-gallery.com/314-custom-circle-packing-with-several-levels_files/figure-html/thecode4b-1.png){width=75%}
</center>
### Circular Packing with Hidden First Level of Hierarchy
This section shows how to build a [circular packing](https://www.r-graph-gallery.com/circular-packing.html) with R and the `ggraph` package, and how to remove the main bubble that packs all the others.
### Hiding the First Level for Better Styling
I personally do not like to display the big circle that surrounds the whole chart (level 0, origin). This circle does not provide any information, and the chart looks better without it in my opinion.
To get rid of it, just specify a color equal to the background color in the `scale_fill_manual()` and `scale_color_manual()` functions. Following the same idea, you can get rid of as many levels of hierarchy as you like.
```r
# Libraries
library(ggraph)
library(igraph)
library(tidyverse)
library(viridis)
# We need a data frame giving a hierarchical structure. Let's consider the flare dataset:
edges=flare$edges
vertices = flare$vertices
mygraph <- graph_from_data_frame( edges, vertices=vertices )
# Hide the first level (right)
ggraph(mygraph, layout = 'circlepack', weight="size") +
geom_node_circle(aes(fill = as.factor(depth), color = as.factor(depth) )) +
scale_fill_manual(values=c("0" = "white", "1" = viridis(4)[1], "2" = viridis(4)[2], "3" = viridis(4)[3], "4"=viridis(4)[4])) +
scale_color_manual( values=c("0" = "white", "1" = "black", "2" = "black", "3" = "black", "4"="black") ) +
theme_void() +
theme(legend.position="FALSE")
```
<center>
![](https://www.r-graph-gallery.com/315-hide-first-level-in-circle-packing_files/figure-html/thecode3a-1.png){width=75%}
</center>
```r
# Second one: hide 2 first levels
ggraph(mygraph, layout = 'circlepack', weight="size") +
geom_node_circle(aes(fill = as.factor(depth), color = as.factor(depth) )) +
scale_fill_manual(values=c("0" = "white", "1" = "white", "2" = magma(4)[2], "3" = magma(4)[3], "4"=magma(4)[4])) +
scale_color_manual( values=c("0" = "white", "1" = "white", "2" = "black", "3" = "black", "4"="black") ) +
theme_void() +
theme(legend.position="FALSE")
```
<center>
![](https://www.r-graph-gallery.com/315-hide-first-level-in-circle-packing_files/figure-html/thecode3b-1.png){width=75%}
</center>
### Add Labels to a Specific Level of the Hierarchy
A related problem consists to add labels for one specific level of hierarchy only. For instance, if you want to display the names of group of level2, but not of level 3 to avoid cluttering the chart.
To solve this issue, the trickiest part is to determine the level of each node in the edge list data frame. Fortunately, the `data.tree` library is here to help with its `FromDataFrameNetwork()` function. It allows to isolate the level of each node, making it a breeze to select the labels to display.
```r
# Add the data.tree library
library(data.tree)
# Rebuild the data
edges <-flare$edges
vertices <- flare$vertices
# Transform it in a 'tree' format
tree <- FromDataFrameNetwork(edges)
# Then I can easily get the level of each node, and add it to the initial data frame:
mylevels <- data.frame( name=tree$Get('name'), level=tree$Get("level") )
vertices <- vertices %>%
left_join(., mylevels, by=c("name"="name"))
# Now we can add label for level1 and 2 only for example:
vertices <- vertices %>%
mutate(new_label=ifelse(level==2, shortName, NA))
mygraph <- graph_from_data_frame( edges, vertices=vertices )
# Make the graph
ggraph(mygraph, layout = 'circlepack', weight="size") +
geom_node_circle(aes(fill = as.factor(depth), color = as.factor(depth) )) +
scale_fill_manual(values=c("0" = "white", "1" = viridis(4)[1], "2" = viridis(4)[2], "3" = viridis(4)[3], "4"=viridis(4)[4])) +
scale_color_manual( values=c("0" = "white", "1" = "black", "2" = "black", "3" = "black", "4"="black") ) +
geom_node_label( aes(label=new_label), size=4) +
theme_void() +
theme(legend.position="FALSE", plot.margin = unit(rep(0,4), "cm"))
```
<center>
![](https://www.r-graph-gallery.com/315-hide-first-level-in-circle-packing_files/figure-html/thecode2-1.png){width=75%}
</center>
### Zoomable Circle Packing with R and circlePacker
The circlePacker package allows to build interactive and zoomable circle packing charts. This section explains how to use the package with different kind of input datasets.
The `circlepackeR` package allows to build interactive [circle packing](https://www.r-graph-gallery.com/circular-packing.html). Click on a group, and a smooth zoom will reveal the subgroups behind it.
Circle packing is a visualization method for hierarchical data. This kind of data can be stored in 2 main ways:
* Nested data frame
* Edge list
<center>
![*Nested data frame*](https://www.r-graph-gallery.com/img/other/Nested_DataFrame.png){width=50%}
</center>
<center>
![*Edge list*](https://www.r-graph-gallery.com/img/other/Hierarchical_network_2col.png){width=25%}
</center>
#### Circular Packing fom Nested Data Frame
In a nested data frame, each line represents a leaf of the organization. Each column represents a level of the organization.
This data format will require the `data.tree` library to reformat the input dataset into something readable by `circlepackeR`.
```r
# Circlepacker package
library(circlepackeR)
# devtools::install_github("jeromefroe/circlepackeR") # If needed
# create a nested data frame giving the info of a nested dataset:
data <- data.frame(
root=rep("root", 15),
group=c(rep("group A",5), rep("group B",5), rep("group C",5)),
subgroup= rep(letters[1:5], each=3),
subsubgroup=rep(letters[1:3], 5),
value=sample(seq(1:15), 15)
)
# Change the format. This use the data.tree library. This library needs a column that looks like root/group/subgroup/..., so I build it
library(data.tree)
data$pathString <- paste("world", data$group, data$subgroup, data$subsubgroup, sep = "/")
population <- as.Node(data)
# Make the plot
#circlepackeR(population, size = "value")
# You can custom the minimum and maximum value of the color range.
p <- circlepackeR(population, size = "value", color_min = "hsl(56,80%,80%)", color_max = "hsl(341,30%,40%)")
p
# save the widget
# library(htmlwidgets)
# saveWidget(p, file=paste0( getwd(), "/HtmlWidget/circular_packing_circlepackeR2.html"))
```
<center>
```{r circular-packing-circlepacker, echo=FALSE}
htmltools::tags$iframe(title = "My embedded document", src = "partHtml/circular_packing_circlepackeR2.html", height="500px", width = "100%")
```
</center>
### Circular Packing fom Edge List
The edge list format has at least 2 columns. It describes all the edges of the data.
This format is widely spread. In this example, we just convert it to a nested data frame before plotting it as seen above.
```r
# Circlepacker package
library(circlepackeR)
# devtools::install_github("jeromefroe/circlepackeR") # If needed
# Let's use the 'flare dataset' (stored in the ggraph library)
library(ggraph)
data_edge <- flare$edges
data_edge$from <- gsub(".*\\.","",data_edge$from)
data_edge$to <- gsub(".*\\.","",data_edge$to)
head(data_edge) # This is an edge list
# We need to convert it to a nested data frame. the data.tree library is our best friend for that:
library(data.tree)
data_tree <- FromDataFrameNetwork(data_edge)
data_nested <- ToDataFrameTree(data_tree,
level1 = function(x) x$path[2],
level2 = function(x) x$path[3],
level3 = function(x) x$path[4],
level4 = function(x) x$path[5])[-1,-1]
data_nested <- na.omit(data_nested)
# Now we can plot it as seen before!
data_nested$pathString <- paste("roots", data_nested$level1, data_nested$level2, data_nested$level3, data_nested$level4, sep = "/")
data_nested$value=1
data_Node <- as.Node(data_nested)
p <- circlepackeR(data_Node, size = "value")
p
# save the widget
# library(htmlwidgets)
# saveWidget(p, file=paste0( getwd(), "/HtmlWidget/circular_packing_circlepackeR1.html"))
```
<center>
```{r circular-packing-circlepacker-two, echo=FALSE}
htmltools::tags$iframe(title = "My embedded document", src = "partHtml/circular_packing_circlepackeR1.html", height="500px", width = "100%")
```
</center>
## Circular Stacked Barchart
---
A barchart can look pretty good using a circular layout, even if there are some [caveats](https://www.data-to-viz.com/caveat/circular_bar_yaxis.html) associated. If it interests you, visit the [circular barchart section](https://www.r-graph-gallery.com/circular-barplot.html).
### Circular Stacked Barplot
A [circular barplot](https://www.r-graph-gallery.com/circular-barplot.html) is a [barplot](https://www.r-graph-gallery.com/barplot.html) where bars are displayed along a circle instead of a line. This page aims to teach you how to make a grouped and stacked circular barplot with `R` and `ggplot2`.
A [circular barplot](https://www.r-graph-gallery.com/circular-barplot.html) is a [barplot]() where bars are displayed along a circle instead of a line. This page aims to teach you how to make a grouped and stacked circular barplot. I highly recommend to visit graph [#295](https://www.r-graph-gallery.com/295-basic-circular-barplot.html), [#296](https://www.r-graph-gallery.com/296-add-labels-to-circular-barplot.html) and [#297](https://www.r-graph-gallery.com/297-circular-barplot-with-groups.html) Before diving into this code, which is a bit rough.
I tried to add as many comments as possible in the code, and thus hope that the method is understandable. If it is not, please comment and ask supplementary explanations.
You first need to understand how to make a [stacked barplot](https://www.r-graph-gallery.com/stacked-barplot.html) with ggplot2. Then understand how to properly add labels, calculating the good angles, flipping them if necessary, and adjusting their position. The trickiest part is probably the one allowing to add space between each group. All these steps are described one by one in the circular barchart [section](https://www.r-graph-gallery.com/circular-barplot.html).
```r
# library
library(tidyverse)
library(viridis)
# Create dataset
data <- data.frame(
individual=paste( "Mister ", seq(1,60), sep=""),
group=c( rep('A', 10), rep('B', 30), rep('C', 14), rep('D', 6)) ,
value1=sample( seq(10,100), 60, replace=T),
value2=sample( seq(10,100), 60, replace=T),
value3=sample( seq(10,100), 60, replace=T)
)
# Transform data in a tidy format (long format)
data <- data %>% gather(key = "observation", value="value", -c(1,2))
# Set a number of 'empty bar' to add at the end of each group
empty_bar <- 2
nObsType <- nlevels(as.factor(data$observation))
to_add <- data.frame( matrix(NA, empty_bar*nlevels(data$group)*nObsType, ncol(data)) )
colnames(to_add) <- colnames(data)
to_add$group <- rep(levels(data$group), each=empty_bar*nObsType )
data <- rbind(data, to_add)
data <- data %>% arrange(group, individual)
data$id <- rep( seq(1, nrow(data)/nObsType) , each=nObsType)
# Get the name and the y position of each label
label_data <- data %>% group_by(id, individual) %>% summarize(tot=sum(value))
number_of_bar <- nrow(label_data)
angle <- 90 - 360 * (label_data$id-0.5) /number_of_bar # I substract 0.5 because the letter must have the angle of the center of the bars. Not extreme right(1) or extreme left (0)
label_data$hjust <- ifelse( angle < -90, 1, 0)
label_data$angle <- ifelse(angle < -90, angle+180, angle)
# prepare a data frame for base lines
base_data <- data %>%
group_by(group) %>%
summarize(start=min(id), end=max(id) - empty_bar) %>%
rowwise() %>%
mutate(title=mean(c(start, end)))
# prepare a data frame for grid (scales)
grid_data <- base_data
grid_data$end <- grid_data$end[ c( nrow(grid_data), 1:nrow(grid_data)-1)] + 1
grid_data$start <- grid_data$start - 1
grid_data <- grid_data[-1,]
# Make the plot
p <- ggplot(data) +
# Add the stacked bar
geom_bar(aes(x=as.factor(id), y=value, fill=observation), stat="identity", alpha=0.5) +
scale_fill_viridis(discrete=TRUE) +
# Add a val=100/75/50/25 lines. I do it at the beginning to make sur barplots are OVER it.
geom_segment(data=grid_data, aes(x = end, y = 0, xend = start, yend = 0), colour = "grey", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_data, aes(x = end, y = 50, xend = start, yend = 50), colour = "grey", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_data, aes(x = end, y = 100, xend = start, yend = 100), colour = "grey", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_data, aes(x = end, y = 150, xend = start, yend = 150), colour = "grey", alpha=1, size=0.3 , inherit.aes = FALSE ) +
geom_segment(data=grid_data, aes(x = end, y = 200, xend = start, yend = 200), colour = "grey", alpha=1, size=0.3 , inherit.aes = FALSE ) +
# Add text showing the value of each 100/75/50/25 lines
ggplot2::annotate("text", x = rep(max(data$id),5), y = c(0, 50, 100, 150, 200), label = c("0", "50", "100", "150", "200") , color="grey", size=6 , angle=0, fontface="bold", hjust=1) +
ylim(-150,max(label_data$tot, na.rm=T)) +
theme_minimal() +
theme(
legend.position = "none",
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
plot.margin = unit(rep(-1,4), "cm")
) +
coord_polar() +
# Add labels on top of each bar
geom_text(data=label_data, aes(x=id, y=tot+10, label=individual, hjust=hjust), color="black", fontface="bold",alpha=0.6, size=5, angle= label_data$angle, inherit.aes = FALSE ) +
# Add base line information
geom_segment(data=base_data, aes(x = start, y = -5, xend = end, yend = -5), colour = "black", alpha=0.8, size=0.6 , inherit.aes = FALSE ) +
geom_text(data=base_data, aes(x = title, y = -18, label=group), hjust=c(1,1,0,0), colour = "black", alpha=0.8, size=4, fontface="bold", inherit.aes = FALSE)
p
# Save at png
#ggsave(p, file="output.png", width=10, height=10)
```
<center>
![](https://www.r-graph-gallery.com/img/graph/299-circular-stacked-barplotBig.png){width=75%}
</center>
### Stacked Barplot for Evolution
Stacked area chart are sometimes used to study an evolution using each group on the X axis as a timestamp. There are many alternatives to that, like [streamgraph](https://www.r-graph-gallery.com/streamgraph.html) or [area chart](https://www.r-graph-gallery.com/area-chart.html):
### Base R
A stacked area chart showing the evolution of a few baby names in the US. <u>Zoom</u> on a specific time frame through <u>brushing</u>. Highlight a specific group by <u>hovering the legend</u>. Double click to unzoom
### Stacking Barplot
```{r stacked-barchart-part, echo=TRUE, fig.height=5, fig.width=5, message=FALSE, warning=FALSE}
# Libraries
library(tidyverse)
library(babynames)
library(streamgraph)
library(viridis)
library(hrbrthemes)
library(plotly)
# Load dataset from github
data <- babynames %>%
filter(name %in% c("Amanda", "Jessica", "Patricia", "Deborah", "Dorothy", "Helen")) %>%
filter(sex=="F")
# Plot
p <- data %>%
ggplot( aes(x=year, y=n, fill=name, text=name)) +
geom_area( ) +
scale_fill_viridis(discrete = TRUE) +
theme(legend.position="none") +
ggtitle("Popularity of American names in the previous 30 years") +
theme_ipsum() +
theme(legend.position="none")
ggplotly(p, tooltip="text")
```
### Three Periods Stacked Barplot
```{r stacked-barchart-three-periods, echo=TRUE, message=FALSE, warning=FALSE}
# create dummy data
don <- data.frame(
x = rep(seq(2000,2005), 3),
value = c( 75, 73, 68, 57, 36, 0, 15, 16, 17, 18, 19, 20, 10, 11, 15, 25, 45, 80),
group = rep(c("A", "B", "C"), each=6)
)
#plot
don %>%
ggplot( aes(x=x, y=value, fill=group)) +
geom_area( ) +
scale_fill_viridis(discrete = TRUE) +
theme(legend.position="none") +
theme_ipsum() +
theme(legend.position="none")
```
### Base R
A stacked area chart showing the evolution of a few baby names in the US. Zoom on a specific time frame through brushing. Highlight a specific group by hovering the legend. Double click to unzoom.
### Grouped, Stacked and Percent Stacked Barplot in Base R
This section explains how to build grouped, stacked and percent stacked barplot with base R. It provides a reproducible example with code for each type.
#### Grouped Barchart
A grouped barplot display a numeric value for a set of entities split in groups and subgroups. Before trying to build one, check how to make a [basic barplot](https://www.r-graph-gallery.com/208-basic-barplot.html) with `R` and `ggplot2`.
A few explanation about the code below:
* Input dataset must be a numeric matrix. Each group is a column. Each subgroup is a row.
* The `barplot()` function will recognize this format, and automatically perform the grouping for you.
* The `beside` allows to toggle between the grouped and the stacked barchart.
```r
# Create data
set.seed(112)
data <- matrix(sample(1:30,15) , nrow=3)
colnames(data) <- c("A","B","C","D","E")
rownames(data) <- c("var1","var2","var3")
# Grouped barplot
barplot(data,
col=colors()[c(23,89,12)] ,
border="white",
font.axis=2,
beside=T,
legend=rownames(data),
xlab="group",
font.lab=2)
```
<center>
![](https://www.r-graph-gallery.com/211-basic-grouped-or-stacked-barplot_files/figure-html/thecode-1.png){width=75%}
</center>
### Grouped Stacked Barchart
A stacked barplot is very similar to the grouped barplot above. The subgroups are just displayed on top of each other, not beside. The stacked barchart is the default option of the `barplot()` function in base R, so you don't need to use the `beside` argument.
```r
# Create data
set.seed(112)
data <- matrix(sample(1:30,15) , nrow=3)
colnames(data) <- c("A","B","C","D","E")
rownames(data) <- c("var1","var2","var3")
# Get the stacked barplot
barplot(data,
col=colors()[c(23,89,12)] ,
border="white",
space=0.04,
font.axis=2,
xlab="group")
```
<center>
![](https://www.r-graph-gallery.com/211-basic-grouped-or-stacked-barplot_files/figure-html/thecode2-1.png){width=75%}
</center>
### Percent Stacked Barplot
A percent stacked barchart displays the evolution of the proportion of each subgroup. The sum is always equal to 100%.
In base R, you have to manually compute the percentages, using the `apply()` function. This is more straightforward using [ggplot2](https://www.r-graph-gallery.com/48-grouped-barplot-with-ggplot2.html).
Note that here, a custom color palette is used, thanks to the `RColorBrewer` package.
```r
# Create data
set.seed(1124)
data <- matrix(sample(1:30,15) , nrow=3)
colnames(data) <- c("A","B","C","D","E")
rownames(data) <- c("var1","var2","var3")
# create color palette:
library(RColorBrewer)
coul <- brewer.pal(3, "Pastel2")
# Transform this data in %
data_percentage <- apply(data, 2, function(x){x*100/sum(x,na.rm=T)})
# Make a stacked barplot--> it will be in %!
barplot(data_percentage, col=coul , border="white", xlab="group")
```
<center>
![](https://www.r-graph-gallery.com/211-basic-grouped-or-stacked-barplot_files/figure-html/thecode3-1.png){width=75%}
</center>
### Barplot for `likert` Type Items
This section shows how to use the likert R package. It allows to build 0-centered stacked barplot to study likert type items.
[Likert](https://github.com/jbryer/likert) is an R package designed to help analyzing and visualizing Likert type items. It has been developped by Jason Bryer and Kim Speerschneider.
This barplot comes from the [demo page](https://github.com/jbryer/likert) and has been sent by [Carlos Ortega](https://www.linkedin.com/in/carlosortegafernandez).
It allows to analyse the reading attitudes from a panel of people. Each line represents a question. The barplot explains the feeling of people concerning this question.
```r
# library
library(likert)
# Use a provided dataset
data(pisaitems)
items28 <- pisaitems[, substr(names(pisaitems), 1, 5) == "ST24Q"]
# Build plot
p <- likert(items28)
plot(p)
```
<center>
![](https://www.r-graph-gallery.com/202-barplot-for-likert-type-items_files/figure-html/thecode-1.png){width=75%}
</center>
## Dendrogram
---
A [dendrogram](https://www.data-to-viz.com/graph/dendrogram.html) (or tree diagram) is a network structure. It is constituted of a root node that gives birth to several nodes connected by edges or branches. The last nodes of the hierarchy are called leaves. Many options are available to build one with R. This sections aims to lead you toward the best strategy for your data.
#### Two Types of Dendrogram
Dendrograms can be built from:
* [Hierarchical dataset](https://www.r-graph-gallery.com/dendrogram.html#hiera): Think about a CEO managing team leads managing employees and so on.
* [Clustering result](https://www.r-graph-gallery.com/dendrogram.html#clust): clustering divides a set of individuals in group according to their similarity. Its result can be visualized as a tree.
### Dendrogram fromn Hierarchical Data
The `ggraph` package is the best option to build a dendrogram from hierarchical data with R. It is based on the grammar of graphic and thus follows the same logic that `ggplot2`.
### Dendrogram from Edge List
This section aims to describe how to make a basic [dendrogram](https://www.r-graph-gallery.com/dendrogram.html) representing hierarchical data with the ggraph library. Two input formats are considered:
* edge list - 2 columns, one row is on connection.
* nested data frame - one row is one path from root to leaf. As many columns as the number of levels in the hierarchy.
Please visit [this page](https://www.r-graph-gallery.com/335-custom-ggraph-dendrogram.html) to learn how to custom these dendrograms. If you want to create a dendrogram from clustering result, visit the [dendrogram section](https://www.r-graph-gallery.com/dendrogram.html) of the gallery.
Edge list is the most convenient format to use `ggraph`. Follow those steps:
* Transform the input dataframe to a graph object using the `graph_from_data_frame()` function from the `igraph` library.
* Use the dendrogram layout of `ggraph` with `layout = 'dendrogram'`.
<center>
![](https://www.r-graph-gallery.com/img/other/Hierarchical_network_2col.png){width=25%}
</center>
```r
# libraries
library(ggraph)
library(igraph)
library(tidyverse)
# create an edge list data frame giving the hierarchical structure of your individuals
d1 <- data.frame(from="origin", to=paste("group", seq(1,5), sep=""))
d2 <- data.frame(from=rep(d1$to, each=5), to=paste("subgroup", seq(1,25), sep="_"))
edges <- rbind(d1, d2)
# Create a graph object
mygraph <- graph_from_data_frame( edges )
# Basic tree
ggraph(mygraph, layout = 'dendrogram', circular = FALSE) +
geom_edge_diagonal() +
geom_node_point() +
theme_void()
```