-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path03-ranking.Rmd
2342 lines (1776 loc) · 88.4 KB
/
03-ranking.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
# Ranking {#ranking}
---
```{r wordcloud-ranking-intro-image, echo=FALSE, fig.align='center', fig.cap="Wordcloud", out.width = '50%'}
knitr::include_graphics("https://www.r-graph-gallery.com/img/graph/196-the-wordcloud2-library4.png")
```
## Barplot
---
Welcome to the [barplot](https://www.data-to-viz.com/graph/barplot.html) section of the R graph gallery. A barplot is used to display the relationship between a numeric and a categorical variable. This section also include stacked barplot and grouped barplot where two levels of grouping are shown.
#### Step by Step - `ggplot2` and `geom_bar()`
`ggplot2` allows to build barplot thanks to the `geom_bar()` function. The examples below will guide you through the basics of this tool:
### Basic Barplot with Ggplot2
This section explains how to draw barplots with `R` and [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html), using the `geom_bar()` function. It starts with the most basic example and describes a few possible customizations.
#### Most basic barplot with `geom_bar()`
This is the most basic barplot you can build using the [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html) package. It follows those steps:
* Always start by calling the `ggplot()` function.
* Then specify the `data` object. It has to be a data frame. And it needs one numeric and one categorical variable.
* Then come thes aesthetics, set in the `aes()` function: set the categorical variable for the X axis, use the numeric for the Y axis
* Finally call `geom_bar()`. You have to specify `stat="identity"` for this kind of dataset.
```{r barplot-basic, echo=TRUE, message=FALSE, warning=FALSE}
# Load ggplot2
library(ggplot2)
# Create data
data <- data.frame(
name=c("A","B","C","D","E") ,
value=c(3,12,5,18,45)
)
# Barplot
ggplot(data, aes(x=name, y=value)) +
geom_bar(stat = "identity")
```
### Control Bar Color
Here are a few different methods to control bar colors. Note that using a legend in this case is not necessary since names are already displayed on the X axis. You can remove it with `theme(legend.position="none")`.
```{r barplot-control-bar-color, echo=TRUE, message=FALSE, warning=FALSE}
# Libraries
library(ggplot2)
# 1: uniform color. Color is for the border, fill is for the inside
ggplot(mtcars, aes(x=as.factor(cyl) )) +
geom_bar(color="blue", fill=rgb(0.1,0.4,0.5,0.7) )
# 2: Using Hue
ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) +
geom_bar( ) +
scale_fill_hue(c = 40) +
theme(legend.position="none")
# 3: Using RColorBrewer
ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) +
geom_bar( ) +
scale_fill_brewer(palette = "Set1") +
theme(legend.position="none")
# 4: Using greyscale:
ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) +
geom_bar( ) +
scale_fill_grey(start = 0.25, end = 0.75) +
theme(legend.position="none")
# 5: Set manualy
ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(cyl) )) +
geom_bar( ) +
scale_fill_manual(values = c("red", "green", "blue") ) +
theme(legend.position="none")
```
### Horizontal Barplot with `coord_flip()`
It often makes sense to turn your [barplot](https://www.r-graph-gallery.com/barplot.htmlv) horizontal. Indeed, it makes the group labels much easier to read. Fortunately, the `coord_flip()` function makes it a breeze.
```{r horiz-barplot, echo=TRUE, message=FALSE, warning=FALSE}
# Load ggplot2
library(ggplot2)
# Create data
data <- data.frame(
name=c("A","B","C","D","E") ,
value=c(3,12,5,18,45)
)
# Barplot
ggplot(data, aes(x=name, y=value)) +
geom_bar(stat = "identity") +
coord_flip()
```
### Control Bar Width with `width`
The `width` argument of the `geom_bar()` function allows to control the bar width. It ranges between 0 and 1, 1 being full width.
See how this can be used to make bar charts with [variable width](https://www.r-graph-gallery.com/81-barplot-with-variable-width.html).
```{r barplot-control-bar-width, echo=TRUE, message=FALSE, warning=FALSE}
# Load ggplot2
library(ggplot2)
# Create data
data <- data.frame(
name=c("A","B","C","D","E") ,
value=c(3,12,5,18,45)
)
# Barplot
ggplot(data, aes(x=name, y=value)) +
geom_bar(stat = "identity", width=0.2)
```
#### What's next?
This section was an overview of ggplot2 [barplots](https://www.r-graph-gallery.com/barplot.html), showing the basic options of `geom_barplot()`. Visit the barplot section for more:
* How to [reorder](https://www.r-graph-gallery.com/267-reorder-a-variable-in-ggplot2.html) your barplot
* How to use [variable bar width](https://www.r-graph-gallery.com/81-barplot-with-variable-width.html)
* What about [error bars](https://www.r-graph-gallery.com/4-barplot-with-error-bar.html)
* Circular [barplots](https://www.r-graph-gallery.com/circular-barplot.html)
### Reorder a Variable with Ggplot2
This section describes how to reorder a variable in a `ggplot2` chart. Several methods are suggested, always providing examples with reproducible code chunks.
Reordering groups in a ggplot2 chart can be a struggle. This is due to the fact that `ggplot2` takes into account the order of the `factor` levels, not the order you observe in your data frame. You can sort your input data frame with `sort()` or `arrange()`, it will never have any impact on your `ggplot2` output.
This section explains how to reorder the level of your factor through several examples. Examples are based on 2 dummy datasets:
```{r barplot-reorder-variable, echo=TRUE, message=FALSE, warning=FALSE}
# Library
library(ggplot2)
library(dplyr)
# Dataset 1: one value per group
data <- data.frame(
name=c("north","south","south-east","north-west","south-west","north-east","west","east"),
val=sample(seq(1,10), 8 )
)
# Dataset 2: several values per group (natively provided in R)
# mpg
```
### Method 1: the `Forecats` Library
The [Forecats library](https://github.com/tidyverse/forcats) is a library from the [tidyverse](https://www.tidyverse.org/) especially made to handle factors in R. It provides a suite of useful tools that solve common problems with factors. The `fact_reorder()` function allows to reorder the factor (`data$name` for example) following the value of another column (`data$val` here)..
```{r barplot-forecats-library-reorder, echo=TRUE, message=FALSE, warning=FALSE}
# load the library
library(forcats)
# Reorder following the value of another column:
data %>%
mutate(name = fct_reorder(name, val)) %>%
ggplot( aes(x=name, y=val)) +
geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) +
coord_flip() +
xlab("") +
theme_bw()
# Reverse side
data %>%
mutate(name = fct_reorder(name, desc(val))) %>%
ggplot( aes(x=name, y=val)) +
geom_bar(stat="identity", fill="#f68060", alpha=.6, width=.4) +
coord_flip() +
xlab("") +
theme_bw()
```
If you have several values per level of your factor, you can specify which function to apply to determine the order. The default is to use the median, but you can use the number of data points per group to make the classification:
```{r barplot-several-values-per-level, echo=TRUE, message=FALSE, warning=FALSE}
# Using median
mpg %>%
mutate(class = fct_reorder(class, hwy, .fun='median')) %>%
ggplot( aes(x=reorder(class, hwy), y=hwy, fill=class)) +
geom_boxplot() +
xlab("class") +
theme(legend.position="none") +
xlab("")
# Using number of observation per group
mpg %>%
mutate(class = fct_reorder(class, hwy, .fun='length' )) %>%
ggplot( aes(x=class, y=hwy, fill=class)) +
geom_boxplot() +
xlab("class") +
theme(legend.position="none") +
xlab("") +
xlab("")
```
The last common operation is to provide a specific order to your levels, you can do so using the `fct_relevel()` function as follow:
```{r barplot-specific-order-levels, echo=TRUE, message=FALSE, warning=FALSE}
# Reorder following a precise order
p <- data %>%
mutate(name = fct_relevel(name,
"north", "north-east", "east",
"south-east", "south", "south-west",
"west", "north-west")) %>%
ggplot( aes(x=name, y=val)) +
geom_bar(stat="identity") +
xlab("")
p
```
### Method 2: Using `dplyr` Only
The `mutate()` function of `dplyr` allows to create a new variable or modify an existing one. It is possible to use it to recreate a factor with a specific order. Here are 2 examples:
* The first use a`rrange()` to sort your data frame, and reorder the factor following this desired order.
* The second specifies a custom order for the factor giving the levels one by one.
```{r barplot-dplyr-mutate-sort-custom-order-levels, echo=TRUE, message=FALSE, warning=FALSE}
data %>%
arrange(val) %>% # First sort by val. This sort the dataframe but NOT the factor levels
mutate(name=factor(name, levels=name)) %>% # This trick update the factor levels
ggplot( aes(x=name, y=val)) +
geom_segment( aes(xend=name, yend=0)) +
geom_point( size=4, color="orange") +
coord_flip() +
theme_bw() +
xlab("")
data %>%
arrange(val) %>%
mutate(name = factor(name, levels=c("north", "north-east", "east", "south-east", "south", "south-west", "west", "north-west"))) %>%
ggplot( aes(x=name, y=val)) +
geom_segment( aes(xend=name, yend=0)) +
geom_point( size=4, color="orange") +
theme_bw() +
xlab("")
```
### Method 3: the `reorder()` Function of Base R
In case your an unconditional user of the good old R, here is how to control the order using the `reorder()` function inside a `with()` call:
```{r barplot-dplyr-reorder-with, echo=TRUE, message=FALSE, warning=FALSE}
# reorder is close to order, but is made to change the order of the factor levels.
mpg$class = with(mpg, reorder(class, hwy, median))
p <- mpg %>%
ggplot( aes(x=class, y=hwy, fill=class)) +
geom_violin() +
xlab("class") +
theme(legend.position="none") +
xlab("")
p
```
### Barplot with Variable Width - Ggplot2
This section explains how to draw a [barplot](https://www.r-graph-gallery.com/barplot.html) with variable bar width using `R` and [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html). It can be useful to represent the sample size available behind each group.
This example shows how to customize bar width in your barchart. It can be used to show the sample size hidden between each category.
It is not possible to draw that kind of chart using `geom_bar()` directly. You need to compute manually the position of each bar extremity using the `cumsum()` function, and plot the result using `geom_rect()`.
<u>Note</u>: if you know what the distribution behind each bar is, don't do a barplot, [show it](https://www.data-to-viz.com/caveat/error_bar.html).
```{r barplot-variable-width, echo=TRUE, message=FALSE, warning=FALSE}
# Load ggplot2
library(ggplot2)
library(hrbrthemes) # for style
# make data
data <- data.frame(
group=c("A ","B ","C ","D ") ,
value=c(33,62,56,67) ,
number_of_obs=c(100,500,459,342)
)
# Calculate the future positions on the x axis of each bar (left border, central position, right border)
data$right <- cumsum(data$number_of_obs) + 30*c(0:(nrow(data)-1))
data$left <- data$right - data$number_of_obs
# Plot
ggplot(data, aes(ymin = 0)) +
geom_rect(aes(xmin = left, xmax = right, ymax = value, colour = group, fill = group)) +
xlab("number of obs") +
ylab("value") +
theme_ipsum() +
theme(legend.position="none")
```
### Barplot with Error Bars
This section describes how to add error bars on your [barplot](https://www.r-graph-gallery.com/barplot.html) using R. Both [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html) and base R solutions are considered. A focus on different types of error bar calculation is made.
#### The `geom_errorbar()` Function
Error bars give a general idea of how precise a measurement is, or conversely, how far from the reported value the true (error free) value might be. If the value displayed on your [barplot](https://www.r-graph-gallery.com/barplot.html) is the result of an aggregation (like the mean value of several data points), you may want to display error bars.
To understand how to build it, you first need to understand how to build a [basic barplot](https://www.r-graph-gallery.com/218-basic-barplots-with-ggplot2.html) with R. Then, you just it to add an extra layer using the `geom_errorbar()` function.
The function takes at least 3 arguments in its aesthetics:
* `ymin` and `ymax`: position of the bottom and the top of the error bar respectively
* `x`: position on the X axis
<u>Note</u>: the lower and upper limits of your error bars must be computed before building the chart, and available in a column of the input data.
```{r barplot-error-bars-basic, echo=TRUE, message=FALSE, warning=FALSE}
# Load ggplot2
library(ggplot2)
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5),
sd=c(1,0.2,3,2,4)
)
# Most basic error bar
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.7) +
geom_errorbar( aes(x=name, ymin=value-sd, ymax=value+sd), width=0.4, colour="orange", alpha=0.9, size=1.3)
```
### Customization
It is possible to change error bar types thanks to similar function: `geom_crossbar()`, `geom_linerange()` and `geom_pointrange()`. Those functions works basically the same as the most common `geom_errorbar()`.
```{r barplot-custom-error-bar-types, echo=TRUE, message=FALSE, warning=FALSE}
# Load ggplot2
library(ggplot2)
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5),
sd=c(1,0.2,3,2,4)
)
# rectangle
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_crossbar( aes(x=name, y=value, ymin=value-sd, ymax=value+sd), width=0.4, colour="orange", alpha=0.9, size=1.3)
# line
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_linerange( aes(x=name, ymin=value-sd, ymax=value+sd), colour="orange", alpha=0.9, size=1.3)
# line + dot
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_pointrange( aes(x=name, y=value, ymin=value-sd, ymax=value+sd), colour="orange", alpha=0.9, size=1.3)
# horizontal
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_errorbar( aes(x=name, ymin=value-sd, ymax=value+sd), width=0.4, colour="orange", alpha=0.9, size=1.3) +
coord_flip()
```
### Basic R and the `barplot()` Function
Basic R can build quality barplots thanks to the `barplot()` function. Here is a list of examples guiding you through the most common customization you will need.
#### Most Basic Barplot
This section describes how to build a basic barplot with R, without any packages, using the `barplot()` function. In R, a barplot is computed using the `barplot()` function.
Here is the most basic example you can do. The input data is a data frame with 2 columns. value is used for bar height, name is used as category label.
```{r barplots-base-r, echo=TRUE, message=FALSE, warning=FALSE}
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# The most basic barplot you can do:
barplot(height=data$value, names=data$name)
```
### Custom Color
Here are 2 examples showing how to custom the barplot color:
* Uniform color with col, asking one color only.
* Using a palette coming from `RColorBrewer`.
* Change border color with the border argument.
```{r barplot-base-r-custom-color, echo=TRUE, message=FALSE, warning=FALSE}
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# Uniform color
barplot(height=data$value, names=data$name, col=rgb(0.2,0.4,0.6,0.6) )
# Specific color for each bar? Use a well known palette
library(RColorBrewer)
coul <- brewer.pal(5, "Set2")
barplot(height=data$value, names=data$name, col=coul )
# Change border color
barplot(height=data$value, names=data$name, border="#69b3a2", col="white" )
```
### Title, Axis label, Custom Limits
Usual customizations with **xlab**, **ylab**, **main** and **ylim**.
```{r barplot-custom-title-axis-label-limits, echo=TRUE, message=FALSE, warning=FALSE}
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# Uniform color
barplot(height=data$value, names=data$name,
col=rgb(0.8,0.1,0.1,0.6),
xlab="categories",
ylab="values",
main="My title",
ylim=c(0,40)
)
```
### Horizontal Barplot
Usual customization with **xlab**, **ylab**, **main** and **ylim**.
```{r horizontal-barplot-custom-width-ylab-main, echo=TRUE, message=FALSE, warning=FALSE}
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# Uniform color
barplot(height=data$value, names=data$name,
col="#69b3a2",
horiz=T, las=1
)
```
### Bar Width & Space between Bars
It is possible to control the space between bars and the width of the bars using space and width.
Can be useful to represent the number of value behind each bar.
```{r horizontal-barplot-width-space-between-bars, echo=TRUE, message=FALSE, warning=FALSE}
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# Control space:
barplot(height=data$value, names=data$name, col=rgb(0.2,0.4,0.6,0.6), space=c(0.1,0.2,3,1.5,0.3) )
# Control width:
barplot(height=data$value, names=data$name, col=rgb(0.2,0.4,0.6,0.6), width=c(0.1,0.2,3,1.5,0.3) )
```
### Barplot Texture
Change bar texture with the density and angle arguments.
```{r horizontal-barplot-density-angle-texture, echo=TRUE, message=FALSE, warning=FALSE}
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# barplot
barplot( height=data$value, names=data$name , density=c(5,10,20,30,7) , angle=c(0,45,90,11,36) , col="brown" )
```
### Advanced R Barplot Customization
Take your base R barplot to the next step: modify axis, label orientation, margins, and more.
#### Start Basic: `barplot()` Function
```{r horizontal-barplot-advanced-axis-label-margins, echo=TRUE, message=FALSE, warning=FALSE}
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# The most basic barplot you can do:
barplot(height=data$value, names=data$name, col="#69b3a2")
```
### Axis Labels Orientation with `las()`
The las argument allows to change the orientation of the axis labels:
* **0**: always parallel to the axis
* **1**: always horizontal
* **2**: always perpendicular to the axis
* **3**: always vertical.
This is specially helpful for horizontal bar chart.
```{r horizontal-barplot-axis-label-orientation-las, echo=TRUE, message=FALSE, warning=FALSE}
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# The most basic barplot you can do:
barplot(height=data$value, names=data$name, col="#69b3a2", horiz=T , las=1)
```
### Change Group Labels with **names.arg**
Change the group names using the **names.arg** argument. The vector you provide must be the same length as the number of categories.
```{r horizontal-barplot-change-group-labels, echo=TRUE, message=FALSE, warning=FALSE}
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# Uniform color
barplot(height=data$value, names.arg=c("group1","group2","group3","group4","group5"), col="#69b3a2")
```
### Axis Labels & Axis Title Style
Customize the labels:
* **font.axis**: font: 1: normal, 2: bold, 3: italic, 4: bold italic
* **col.axis**: color
* **cex.axis**: size
Customize axis title:
* **font.lab**
* **col.lab**
* **cex.lab**
```{r horizontal-barplot-axis-label-and-axis-title-style, echo=TRUE, message=FALSE, warning=FALSE}
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# Customize labels (left)
barplot(height=data$value, names=data$name,
names.arg=c("group1","group2","group3","group4","group5"),
font.axis=2,
col.axis="orange",
cex.axis=1.5
)
# Customize title (right)
barplot(height=data$value, names=data$name,
xlab="category",
font.lab=2,
col.lab="orange",
cex.lab=2
)
```
### Increase Margin Size
If your group names are long, you need to:
* Rotate them to avoid overlapping. This is done with las
* Increase bottom margin size using the mar parameter of the `par()` function. Four values are provided: **bottom**, **left**, **top**, **right** respectively.
Note: prefer a horizontal barplot in this case.
```{r horizontal-barplot-increase-margin-size, echo=TRUE, message=FALSE, warning=FALSE}
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5)
)
# Increase margin size
par(mar=c(11,4,4,4))
# Uniform color
barplot(height=data$value,
col="#69b3a2",
names.arg=c("very long group name 1","very long group name 2","very long group name 3","very long group name 4","very long group name 5"),
las=2
)
```
### Barplot with Error Bars
This section describes how to add error bars on your barplot using R. Both ggplot2 and base R solutions are considered. A focus on different types of error bar calculation is made.
#### The `geom_errorbar()` Function
Error bars give a general idea of how precise a measurement is, or conversely, how far from the reported value the true (error free) value might be. If the value displayed on your barplot is the result of an aggregation (like the mean value of several data points), you may want to display error bars.
To understand how to build it, you first need to understand how to build a basic barplot with R. Then, you just it to add an extra layer using the `geom_errorbar()` function.
The function takes at least 3 arguments in its aesthetics:
* **ymin** and **ymax**: position of the bottom and the top of the error bar respectively
* **x**: position on the X axis
Note: the lower and upper limits of your error bars must be computed before building the chart, and available in a column of the input data.
```{r barplot-error-bars-ggplot, echo=TRUE, message=FALSE, warning=FALSE}
# Load ggplot2
library(ggplot2)
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5),
sd=c(1,0.2,3,2,4)
)
# Most basic error bar
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.7) +
geom_errorbar( aes(x=name, ymin=value-sd, ymax=value+sd), width=0.4, colour="orange", alpha=0.9, size=1.3)
```
### Customization
It is possible to change error bar types thanks to similar function: `geom_crossbar()`, `geom_linerange()` and `geom_pointrange()`. Those functions works basically the same as the most common `geom_errorbar()`.
```{r barplot-error-bar-custom, echo=TRUE, message=FALSE, warning=FALSE}
#Load ggplot2
library(ggplot2)
# create dummy data
data <- data.frame(
name=letters[1:5],
value=sample(seq(4,15),5),
sd=c(1,0.2,3,2,4)
)
# rectangle
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_crossbar( aes(x=name, y=value, ymin=value-sd, ymax=value+sd), width=0.4, colour="orange", alpha=0.9, size=1.3)
# line
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_linerange( aes(x=name, ymin=value-sd, ymax=value+sd), colour="orange", alpha=0.9, size=1.3)
# line + dot
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_pointrange( aes(x=name, y=value, ymin=value-sd, ymax=value+sd), colour="orange", alpha=0.9, size=1.3)
# horizontal
ggplot(data) +
geom_bar( aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.5) +
geom_errorbar( aes(x=name, ymin=value-sd, ymax=value+sd), width=0.4, colour="orange", alpha=0.9, size=1.3) +
coord_flip()
```
### Standard Deviation, Standard Error or Confidence Interval?
Three different types of values are commonly used for error bars, sometimes without even specifying which one is used. It is important to understand how they are calculated, since they give very different results (see above). Let's compute them on a simple vector:
```r
vec=c(1,3,5,9,38,7,2,4,9,19,19)
```
#### Standard Deviation (SD)
It represents the amount of dispersion of the variable. Calculated as the root square of the variance:
```r
sd <- sd(vec)
sd <- sqrt(var(vec))
sd
```
#### Standard Error (SE)
It is the standard deviation of the vector sampling distribution. Calculated as the SD divided by the square root of the sample size. By construction, SE is smaller than SD. With a very big sample size, SE tends toward 0.
```r
se = sd(vec) / sqrt(length(vec))
se
```
#### Confidence Interval (CI)
This interval is defined so that there is a specified probability that a value lies within it. It is calculated as t * SE. Where t is the value of the Student's t-distribution for a specific alpha. Its value is often rounded to 1.96 (its value with a big sample size). If the sample size is huge or the distribution not normal, it is better to calculate the CI using the bootstrap method, however.
```r
alpha=0.05
t=qt((1-alpha)/2 + .5, length(vec)-1) # tend to 1.96 if sample size is big enough
CI=t*se
CI
```
After this short introduction, here is how to compute these 3 values for each group of your dataset, and use them as error bars on your [barplot](https://www.r-graph-gallery.com/barplot.html). As you can see, the differences can greatly influence your conclusions.
```{r sd-se-ci-plot, echo=TRUE, message=FALSE, warning=FALSE}
# Load ggplot2
library(ggplot2)
library(dplyr)
# Data
data <- iris %>% dplyr::select(Species, Sepal.Length)
# Calculates mean, sd, se and IC
my_sum <- data %>%
group_by(Species) %>%
summarise(
n=n(),
mean=mean(Sepal.Length),
sd=sd(Sepal.Length)
) %>%
mutate( se=sd/sqrt(n)) %>%
mutate( ic=se * qt((1-0.05)/2 + .5, n-1))
# Standard deviation
ggplot(my_sum) +
geom_bar( aes(x=Species, y=mean), stat="identity", fill="forestgreen", alpha=0.5) +
geom_errorbar( aes(x=Species, ymin=mean-sd, ymax=mean+sd), width=0.4, colour="orange", alpha=0.9, size=1.5) +
ggtitle("using standard deviation")
# Standard Error
ggplot(my_sum) +
geom_bar( aes(x=Species, y=mean), stat="identity", fill="forestgreen", alpha=0.5) +
geom_errorbar( aes(x=Species, ymin=mean-se, ymax=mean+se), width=0.4, colour="orange", alpha=0.9, size=1.5) +
ggtitle("using standard error")
# Confidence Interval
ggplot(my_sum) +
geom_bar( aes(x=Species, y=mean), stat="identity", fill="forestgreen", alpha=0.5) +
geom_errorbar( aes(x=Species, ymin=mean-ic, ymax=mean+ic), width=0.4, colour="orange", alpha=0.9, size=1.5) +
ggtitle("using confidence interval")
```
### Basic R: Use the `arrows()` Function
It is double to add error bars with base R only as well, but requires more work. In any case, everything relies on the `arrows()` function.
Let's build a dataset : height of 10 sorgho and poacee sample in 3 environmental conditions (A, B, C)
```{r horizontal-barplot-base-r-arrow, warning=FALSE, message=FALSE}
#Let's build a dataset : height of 10 sorgho and poacee sample in 3 environmental conditions (A, B, C)
data <- data.frame(
specie=c(rep("sorgho" , 10) , rep("poacee" , 10) ),
cond_A=rnorm(20,10,4),
cond_B=rnorm(20,8,3),
cond_C=rnorm(20,5,4)
)
#Let's calculate the average value for each condition and each specie with the *aggregate* function
bilan <- aggregate(cbind(cond_A,cond_B,cond_C)~specie , data=data , mean)
rownames(bilan) <- bilan[,1]
bilan <- as.matrix(bilan[,-1])
#Plot boundaries
lim <- 1.2*max(bilan)
#A function to add arrows on the chart
error.bar <- function(x, y, upper, lower=upper, length=0.1,...){
arrows(x,y+upper, x, y-lower, angle=90, code=3, length=length, ...)
}
#Then I calculate the standard deviation for each specie and condition :
stdev <- aggregate(cbind(cond_A,cond_B,cond_C)~specie , data=data , sd)
rownames(stdev) <- stdev[,1]
stdev <- as.matrix(stdev[,-1]) * 1.96 / 10
#I am ready to add the error bar on the plot using my "error bar" function !
ze_barplot <- barplot(bilan , beside=T , legend.text=T,col=c("blue" , "skyblue") , ylim=c(0,lim) , ylab="height")
error.bar(ze_barplot,bilan, stdev)
```
### Barplot with Number of Observation
A barplot with number of observation on top of bars, legend, ablines, increased margin and more.
This chart illustrates many tips you can apply to a base R barplot:
* Add abline with `abline()`
* Change axis labels orientation with `las()`
* Add text with `text()`
* Add a legend with `legend()`
```{r barplot-number-oberservations, echo=TRUE, message=FALSE, warning=FALSE}
# Data
data <- data.frame(
name = c("DD","with himself","with DC","with Silur" ,"DC","with himself","with DD","with Silur" ,"Silur","with himself","with DD","with DC" ),
average = sample(seq(1,10) , 12 , replace=T),
number = sample(seq(4,39) , 12 , replace=T)
)
# Increase bottom margin
par(mar=c(6,4,4,4))
# Basic Barplot
my_bar <- barplot(data$average , border=F , names.arg=data$name ,
las=2 ,
col=c(rgb(0.3,0.1,0.4,0.6) , rgb(0.3,0.5,0.4,0.6) , rgb(0.3,0.9,0.4,0.6) , rgb(0.3,0.9,0.4,0.6)) ,
ylim=c(0,13) ,
main="" )
# Add abline
abline(v=c(4.9 , 9.7) , col="grey")
# Add the text
text(my_bar, data$average+0.4 , paste("n: ", data$number, sep="") ,cex=1)
#Legende
legend("topleft", legend = c("Alone","with Himself","With other genotype" ) ,
col = c(rgb(0.3,0.1,0.4,0.6) , rgb(0.3,0.5,0.4,0.6) , rgb(0.3,0.9,0.4,0.6) , rgb(0.3,0.9,0.4,0.6)) ,
bty = "n", pch=20 , pt.cex = 2, cex = 0.8, horiz = FALSE, inset = c(0.05, 0.05))
```
## Circular Barplot
---
This is the [circular barplot](https://www.data-to-viz.com/graph/circularbarplot.html) section of the gallery, a variation of the well known [barplot](https://www.r-graph-gallery.com/barplot.html). Note that even if visually appealing, circular barplot must be used with care since groups [do not share the same Y axis](https://www.data-to-viz.com/graph/circularbarplot.html). It is very adapted for cyclical data though. Visit [data-to-viz.com](https://www.data-to-viz.com/graph/circularbarplot.html) for more info.
#### Step by Step
Here is a set of examples leading to a proper circular barplot, step by step. The first [most basic circular barchart](https://www.r-graph-gallery.com/295-basic-circular-barplot.html) shows how to use `coord_polar()` to make the barchart circular. Next examples describe the next steps to get a proper figure: [gap](https://www.r-graph-gallery.com/297-circular-barplot-with-groups.html) between groups, [labels](https://www.r-graph-gallery.com/296-add-labels-to-circular-barplot.html) and customization.
### Most Basic Circular Barplot
A circular [barplot](https://www.r-graph-gallery.com/barplot.html) is a barplot where bars are displayed along a circle instead of a line. This section explains how to build a basic version with `R` and [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html). It provides the reproducible code and explain how the `coord_polar()` function works.
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. The input dataset is the same than for a barplot: we need one numeric value per group (one group = one bar). (See more explanation in the [barplot](https://www.r-graph-gallery.com/barplot.html) section).
Basically, the method is the same than to do a classic barplot. At the end, we call `coord_polar()` to make the chart circular. Note that the `ylim()` argument is really important. If it starts at 0, the bars will start from the centre of the circle. If you provide a negative value, a white circle space will appear!
This chart is not really insightful, go to the [next example](https://www.r-graph-gallery.com/296-add-labels-to-circular-barplot.html) to learn how to add labels!
```r
# Libraries
library(tidyverse)
# Create dataset
data <- data.frame(
id=seq(1,60),
individual=paste( "Mister ", seq(1,60), sep=""),
value=sample( seq(10,100), 60, replace=T)
)
# Make the plot
p <- ggplot(data, aes(x=as.factor(id), y=value)) + # Note that id is a factor. If x is numeric, there is some space between the first bar
# This add the bars with a blue color
geom_bar(stat="identity", fill=alpha("blue", 0.3)) +
# Limits of the plot = very important. The negative value controls the size of the inner circle, the positive one is useful to add size over each bar
ylim(-100,120) +
# Custom the theme: no axis title and no cartesian grid
theme_minimal() +
theme(
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
plot.margin = unit(rep(-2,4), "cm") # This remove unnecessary margin around plot
) +
# This makes the coordinate polar instead of cartesian.
coord_polar(start = 0)
p
```
![](https://www.r-graph-gallery.com/295-basic-circular-barplot_files/figure-html/thecode-1.png)
### Add Labels to Circular Barplot
This section explains how to add labels on a [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html) circular barchart, on top of each bar. It follows the previous most basic circular barchart.
The [chart #295](https://www.r-graph-gallery.com/295-basic-circular-barplot.html) explains how to make a basic circular barplot. The next step is to add labels to each bar, to give insight to the graphic.
Here I suggest a method to add label at the top of each bar, using the same angle that the central part of the bar. In the code below, a short section creates a dataframe with the feature of each label, that we can then call in `geom_text()`.
Note that labels are always in an angle that allows to read them easily, what requires a 180 degrees flip for some of them.
```r
# Libraries
library(tidyverse)
# Create dataset
data <- data.frame(
id=seq(1,60),
individual=paste( "Mister ", seq(1,60), sep=""),
value=sample( seq(10,100), 60, replace=T)
)
# ----- This section prepare a dataframe for labels ---- #
# Get the name and the y position of each label
label_data <- data
# calculate the ANGLE of the labels
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)
# calculate the alignment of labels: right or left
# If I am on the left part of the plot, my labels have currently an angle < -90
label_data$hjust<-ifelse( angle < -90, 1, 0)
# flip angle BY to make them readable
label_data$angle<-ifelse(angle < -90, angle+180, angle)
# ----- ------------------------------------------- ---- #
# Start the plot
p <- ggplot(data, aes(x=as.factor(id), y=value)) + # Note that id is a factor. If x is numeric, there is some space between the first bar
# This add the bars with a blue color
geom_bar(stat="identity", fill=alpha("skyblue", 0.7)) +
# Limits of the plot = very important. The negative value controls the size of the inner circle, the positive one is useful to add size over each bar
ylim(-100,120) +
# Custom the theme: no axis title and no cartesian grid
theme_minimal() +
theme(
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
plot.margin = unit(rep(-1,4), "cm") # Adjust the margin to make in sort labels are not truncated!
) +
# This makes the coordinate polar instead of cartesian.
coord_polar(start = 0) +
# Add the labels, using the label_data dataframe that we have created before
geom_text(data=label_data, aes(x=id, y=value+10, label=individual, hjust=hjust), color="black", fontface="bold",alpha=0.6, size=2.5, angle= label_data$angle, inherit.aes = FALSE )
p
```
![](https://www.r-graph-gallery.com/296-add-labels-to-circular-barplot_files/figure-html/thecode-1.png)
### Circular Barplot with Groups
This section explains how to build a [circular barchart](https://www.r-graph-gallery.com/circular-barplot.html) with groups. A gap is added between groups to highlight them. Bars are labeled, group names are annotated
#### Add a Gap in the Circle
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 circular barplot with groups.
Since this kind of chart is a bit tricky, I strongly advise to understand [graph #295](https://www.r-graph-gallery.com/295-basic-circular-barplot.html) and [#296](https://www.r-graph-gallery.com/296-add-labels-to-circular-barplot.html) that will teach you the basics.
The first step is to build a circular barplot with a break in the circle. Actually, I just added a few empty lines at the end of the initial data frame:
```r
# library
library(tidyverse)
# Create dataset
data <- data.frame(
individual=paste( "Mister ", seq(1,60), sep=""),
value=sample( seq(10,100), 60, replace=T)
)
# Set a number of 'empty bar'
empty_bar <- 10
# Add lines to the initial dataset
to_add <- matrix(NA, empty_bar, ncol(data))
colnames(to_add) <- colnames(data)
data <- rbind(data, to_add)
data$id <- seq(1, nrow(data))
# Get the name and the y position of each label
label_data <- data
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)
# Make the plot
p <- ggplot(data, aes(x=as.factor(id), y=value)) + # Note that id is a factor. If x is numeric, there is some space between the first bar
geom_bar(stat="identity", fill=alpha("green", 0.3)) +
ylim(-100,120) +
theme_minimal() +
theme(
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
plot.margin = unit(rep(-1,4), "cm")
) +
coord_polar(start = 0) +
geom_text(data=label_data, aes(x=id, y=value+10, label=individual, hjust=hjust), color="black", fontface="bold",alpha=0.6, size=2.5, angle= label_data$angle, inherit.aes = FALSE )
p
```
![](https://www.r-graph-gallery.com/297-circular-barplot-with-groups_files/figure-html/thecode-1.png)
### Space between Groups