-
Notifications
You must be signed in to change notification settings - Fork 4
/
02-correlation.Rmd
2800 lines (2210 loc) · 116 KB
/
02-correlation.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
# Correlation {#correlation}
---
```{r heatmap-correlation-intro-image, echo=FALSE, fig.align='center', fig.cap="Heatmap Normalization", out.width = '50%'}
knitr::include_graphics("https://www.r-graph-gallery.com/215-the-heatmap-function_files/figure-html/thecode2-1.png")
```
## Bubble Plot
---
A [bubble plot](https://www.data-to-viz.com/graph/bubble.html) is a [scatter plot](https://www.r-graph-gallery.com/scatterplot.html) with a third numeric variable mapped to circle size. This page describes several methods to build one with R.
#### A Bubble Chart is a Scatterplot
A bubble chart is basically a [scatterplot](https://www.r-graph-gallery.com/scatterplot.html) with a third numeric variable used for circle size. Thus, remember all the tips described in the [scatterplot section](https://www.r-graph-gallery.com/scatterplot.html) also apply here.
#### Step by Step with `ggplot2`
`ggplot2` allows to create bubble chart thanks to the `geom_point()` function. Next examples will lead you through the process step by step:
### Most Basic bubble Chart with `geom_point()`
A [bubble plot](https://www.r-graph-gallery.com/bubble-chart.html) is a [scatterplot](https://www.r-graph-gallery.com/scatterplot.html) where a third dimension is added: the value of an additional numeric variable is represented through the size of the dots. (source: [data-to-viz](https://www.data-to-viz.com/graph/bubble.html)).
With [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html), bubble chart are built thanks to the `geom_point()` function. At least three variable must be provided to `aes()`: **x**, **y** and **size**. The legend will automatically be built by ggplot2.
Here, the relationship between life expectancy (`y`) and gdp per capita (`x`) of world countries is represented. The population of each country is represented through circle size.
```{r bubble-plot-correlation-ggplot, echo=TRUE, message=FALSE, warning=FALSE}
# Libraries
library(ggplot2)
library(dplyr)
# The dataset is provided in the gapminder library
library(gapminder)
data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)
# Most basic bubble plot
ggplot(data, aes(x=gdpPercap, y=lifeExp, size = pop)) +
geom_point(alpha=0.7)
```
### Control Circle Size with `scale_size()`
The first thing we need to improve on the previous chart is the bubble size. `scale_size()` allows to set the size of the smallest and the biggest circles using the `range` argument. Note that you can customize the legend name with `name`.
<u>Note</u>: circles often overlap. To avoid having big circles on top of the chart you have to reorder your dataset first, as in the code below.
<u>ToDo</u>: give more details about how to map a numeric variable to circle size. Use of `scale_radius`, `scale_size` and `scale_size_area`. [See this post](https://www.data-to-viz.com/caveat/radius_or_area.html).
```{r bubble-plot-correlation-ggplot-control-circle-size, echo=TRUE, message=FALSE, warning=FALSE}
# Libraries
library(ggplot2)
library(dplyr)
# The dataset is provided in the gapminder library
library(gapminder)
data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)
# Most basic bubble plot
data %>%
arrange(desc(pop)) %>%
mutate(country = factor(country, country)) %>%
ggplot(aes(x=gdpPercap, y=lifeExp, size = pop)) +
geom_point(alpha=0.5) +
scale_size(range = c(.1, 24), name="Population (M)")
```
### Add a Fourth Dimension: Color
If you have one more variable in your dataset, why not showing it using circle color? Here, the continent of each country is used to control circle color:
```{r bubble-plot-correlation-ggplot-color-fourth-dimension, echo=TRUE, message=FALSE, warning=FALSE}
# Libraries
library(ggplot2)
library(dplyr)
# The dataset is provided in the gapminder library
library(gapminder)
data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)
# Most basic bubble plot
data %>%
arrange(desc(pop)) %>%
mutate(country = factor(country, country)) %>%
ggplot(aes(x=gdpPercap, y=lifeExp, size=pop, color=continent)) +
geom_point(alpha=0.5) +
scale_size(range = c(.1, 24), name="Population (M)")
```
### Make it Pretty
A few classic improvement:
* Use of the `viridis` package for nice color palette.
* Use of `theme_ipsum()` of the `hrbrthemes` package.
* Custom axis titles with `xlab` and `ylab`.
* Add stroke to circle: change `shape` to 21 and specify `color` (stroke) and `fill`.
```{r bubble-plot-correlation-ggplot-improvements, echo=TRUE, message=FALSE, warning=FALSE}
# Libraries
library(ggplot2)
library(dplyr)
library(hrbrthemes)
library(viridis)
# The dataset is provided in the gapminder library
library(gapminder)
data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)
# Most basic bubble plot
data %>%
arrange(desc(pop)) %>%
mutate(country = factor(country, country)) %>%
ggplot(aes(x=gdpPercap, y=lifeExp, size=pop, fill=continent)) +
geom_point(alpha=0.5, shape=21, color="black") +
scale_size(range = c(.1, 24), name="Population (M)") +
scale_fill_viridis(discrete=TRUE, guide=FALSE, option="A") +
theme_ipsum() +
theme(legend.position="bottom") +
ylab("Life Expectancy") +
xlab("Gdp per Capita") +
theme(legend.position = "none")
```
### Interactive Version
Here is an interactive bubble chart built in R, thanks to the `ggplotly()` function of the `plotly` library. Try to hover circles to get a tooltip, or select an area of interest for zooming. Double click to reinitialize.
#### Interactive Bubble Chart
This section explains how to build an interactive [bubble chart](https://www.r-graph-gallery.com/bubble-chart.html) with R, using `ggplot2` and the `ggplotly()` function of the plotly package.
#### Most Basic Bubble Chart with `geom_point()`
This section follows the previous [step by step description](https://www.r-graph-gallery.com/320-the-basis-of-bubble-plot.html) of building [bubble chart](https://www.r-graph-gallery.com/bubble-chart.html) with [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html).
The idea is to turn the chart interactive:
* You can zoom by selecting an area of interest
* Hover a circle to get information about it
* Export to png
* Slide axis
* Double click to re-initialize.
This is done thanks to the `ggplotly()` function of the `plotly` package that turn any ggplot2 chart object interactive. Note the little trick to custom the tooltip content.
```{r bubble-plot-correlation-ggplot-interactive, echo=TRUE, message=FALSE, warning=FALSE}
# Libraries
library(ggplot2)
library(dplyr)
library(plotly)
library(viridis)
library(hrbrthemes)
# The dataset is provided in the gapminder library
library(gapminder)
data <- gapminder %>% filter(year=="2007") %>% dplyr::select(-year)
# Interactive version
p <- data %>%
mutate(gdpPercap=round(gdpPercap,0)) %>%
mutate(pop=round(pop/1000000,2)) %>%
mutate(lifeExp=round(lifeExp,1)) %>%
# Reorder countries to having big bubbles on top
arrange(desc(pop)) %>%
mutate(country = factor(country, country)) %>%
# prepare text for tooltip
mutate(text = paste("Country: ", country, "\nPopulation (M): ", pop, "\nLife Expectancy: ", lifeExp, "\nGdp per capita: ", gdpPercap, sep="")) %>%
# Classic ggplot
ggplot( aes(x=gdpPercap, y=lifeExp, size = pop, color = continent, text=text)) +
geom_point(alpha=0.7) +
scale_size(range = c(1.4, 19), name="Population (M)") +
scale_color_viridis(discrete=TRUE, guide=FALSE) +
theme_ipsum() +
theme(legend.position="none")
# turn ggplot interactive with plotly
pp <- ggplotly(p, tooltip="text")
pp
# save the widget
# library(htmlwidgets)
# saveWidget(pp, file=paste0( getwd(), "/HtmlWidget/ggplotlyBubblechart.html"))
```
## Connected Scatterplot
---
Welcome to the [connected scatterplot](https://www.data-to-viz.com/graph/connectedscatter.html) section of the gallery. If you want to know more about this kind of chart, visit [data-to-viz.com](https://www.data-to-viz.com/graph/connectedscatter.html). If you're looking for a simple way to implement it in R and `ggplot2`, pick an example below.
### Connected Scatterplot with R and Ggplot2
This section explains how to build a basic [connected scatterplot](https://www.r-graph-gallery.com/connected-scatterplot.html) with R and [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html). It provides several reproducible examples with explanation and R code.
#### Most Basic Connected Scatterplot: `geom_point()` and `geom_line()`
A [connected scatterplot](https://www.r-graph-gallery.com/connected-scatterplot.html) is basically a hybrid between a [scatterplot](https://www.r-graph-gallery.com/scatterplot.html) and a line plot. Thus, you just have to add a `geom_point()` on top of the `geom_line()` to build it.
```r
# Libraries
library(ggplot2)
library(dplyr)
# Load dataset from github
data <- read.table("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/3_TwoNumOrdered.csv", header=T)
data$date <- as.Date(data$date)
# Plot
data %>%
tail(10) %>%
ggplot( aes(x=date, y=value)) +
geom_line() +
geom_point()
```
![](https://www.r-graph-gallery.com/connected_scatterplot_ggplot2_files/figure-html/thecode-1.png)
### Customize the Connected Scatterplot
Custom the general theme with the `theme_ipsum()` function of the hrbrthemes package. Add a title with `ggtitle()`. Custom circle and line with arguments like `shape`, `size`, `color` and more.
```r
# Libraries
library(ggplot2)
library(dplyr)
library(hrbrthemes)
# Load dataset from github
data <- read.table("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/3_TwoNumOrdered.csv", header=T)
data$date <- as.Date(data$date)
# Plot
data %>%
tail(10) %>%
ggplot( aes(x=date, y=value)) +
geom_line( color="grey") +
geom_point(shape=21, color="black", fill="#69b3a2", size=6) +
theme_ipsum() +
ggtitle("Evolution of bitcoin price")
```
![](https://www.r-graph-gallery.com/connected_scatterplot_ggplot2_files/figure-html/thecode2-1.png)
### Connected Scatterplot to show an Evolution
The [connected scatterplot](https://www.r-graph-gallery.com/connected-scatter.html) can also be a powerfull technique to tell a story about the evolution of 2 variables. Let???s consider a dataset composed of 3 columns:
* Year
* Number of baby born called Amanda this year
* Number of baby born called Ashley
The scatterplot beside allows to understand the evolution of these 2 names. Note that the code is pretty different in this case. `geom_segment()` is used of `geom_line()`. This is because `geom_line()` automatically sort data points depending on their X position to link them.
```r
# Libraries
library(ggplot2)
library(dplyr)
library(babynames)
library(ggrepel)
library(tidyr)
# data
data <- babynames %>%
filter(name %in% c("Ashley", "Amanda")) %>%
filter(sex=="F") %>%
filter(year>1970) %>%
dplyr::select(year, name, n) %>%
spread(key = name, value=n, -1)
# plot
data %>%
ggplot(aes(x=Amanda, y=Ashley, label=year)) +
geom_point() +
geom_segment(aes(
xend=c(tail(Amanda, n=-1), NA),
yend=c(tail(Ashley, n=-1), NA)
)
)
```
<center>
![](https://www.r-graph-gallery.com/connected_scatterplot_ggplot2_files/figure-html/thecode3-1.png){width=75%}
</center>
It makes sense to add arrows and labels to guide the reader in the chart:
```r
# data
data <- babynames %>%
filter(name %in% c("Ashley", "Amanda")) %>%
filter(sex=="F") %>%
filter(year>1970) %>%
dplyr::select(year, name, n) %>%
spread(key = name, value=n, -1)
# Select a few date to label the chart
tmp_date <- data %>% sample_frac(0.3)
# plot
data %>%
ggplot(aes(x=Amanda, y=Ashley, label=year)) +
geom_point(color="#69b3a2") +
geom_text_repel(data=tmp_date) +
geom_segment(color="#69b3a2",
aes(
xend=c(tail(Amanda, n=-1), NA),
yend=c(tail(Ashley, n=-1), NA)
),
arrow=arrow(length=unit(0.3,"cm"))
) +
theme_ipsum()
```
<center>
![](https://www.r-graph-gallery.com/connected_scatterplot_ggplot2_files/figure-html/thecode4-1.png){width=75%}
</center>
### Connected Scatterplot for `Time Series`
Connected scatterplots are often used for [time series](https://www.r-graph-gallery.com/time-series.html). Remember the R graph gallery offers a dedicated section, with heaps of examples. For instance, here is an interactive chart made with the [dygraphs](https://www.r-graph-gallery.com/time-series.html) library.
```r
# Library
library(dygraphs)
library(xts) # To make the convertion data-frame / xts format
library(tidyverse)
library(lubridate)
# Read the data (hosted on the gallery website)
data <- read.table("https://python-graph-gallery.com/wp-content/uploads/bike.csv", header=T, sep=",") %>% head(300)
# Check type of variable
# str(data)
# Since my time is currently a factor, I have to convert it to a date-time format!
data$datetime <- ymd_hms(data$datetime)
# Then you can create the xts necessary to use dygraph
don <- xts(x = data$count, order.by = data$datetime)
# Finally the plot
p <- dygraph(don) %>%
dyOptions(labelsUTC = TRUE, fillGraph=TRUE, fillAlpha=0.1, drawGrid = FALSE, colors="#D8AE5A") %>%
dyRangeSelector() %>%
dyCrosshair(direction = "vertical") %>%
dyHighlight(highlightCircleSize = 5, highlightSeriesBackgroundAlpha = 0.2, hideOnMouseOut = FALSE) %>%
dyRoller(rollPeriod = 1)
# save the widget
# library(htmlwidgets)
# saveWidget(p, file=paste0( getwd(), "/HtmlWidget/dygraphs318.html"))
```
<center>
```{r correlation-dygraphs318, echo=FALSE}
htmltools::tags$iframe(title = "My embedded document", src = "evolutionHtml/dygraphs318.html", height="400px", width = "100%")
```
</center>
### Connected Scatterplot using Base R
Basic R also allows to build connected scatterplot thanks to the `line()` function. You just need to use the `b` option of the `type` argument. See examples below.
#### Add a Legend to a Base R Chart
This section explains how to add a legend to a chart made with base R, using the `legend()` function. It provides several reproducible examples with explanation and `R` code. It is done using the `legend()` function. The main arguments are:
This page aims to explain how to add a legend to a plot made in base R. It is done using the `legend()` function. The main arguments are:
* `legend`: names to display
* `bty`: type of box around the legend. See [graph #73](https://www.r-graph-gallery.com/73-box-style-with-the-bty-function.html)
* `horiz`: legend in column or in row
* `col`: symbol color
* `pch`: symbol type. See [graph #6](https://www.r-graph-gallery.com/6-graph-parameters-reminder.html)
* `pt.cex`: symbol size
* `cex`: text size
* `text.col`: text color
* `topright`: legend position: `bottomright`, `bottom`, `bottomleft`, `left`, `topleft`, `top`, `topright`, `right`, `center`
* `inset`: % (from 0 to 1) to draw the legend away from x and y axis
You can also give the `X` and `Y` coordinate of the legend: `legend(3, 5, ...)`
Note that an equivalent page exist concerning [legends with ggplot2](https://www.r-graph-gallery.com/239-custom-layout-legend-ggplot2.html).
```r
# Create data:
a=c(1:5)
b=c(5,3,4,5,5)
c=c(4,5,4,3,1)
# Make a basic graph
plot( b~a , type="b" , bty="l" , xlab="value of a" , ylab="value of b" , col=rgb(0.2,0.4,0.1,0.7) , lwd=3 , pch=17 , ylim=c(1,5) )
lines(c ~a , col=rgb(0.8,0.4,0.1,0.7) , lwd=3 , pch=19 , type="b" )
# Add a legend
legend("bottomleft",
legend = c("Group 1", "Group 2"),
col = c(rgb(0.2,0.4,0.1,0.7),
rgb(0.8,0.4,0.1,0.7)),
pch = c(17,19),
bty = "n",
pt.cex = 2,
cex = 1.2,
text.col = "black",
horiz = F ,
inset = c(0.1, 0.1))
```
![](https://www.r-graph-gallery.com/119-add-a-legend-to-a-plot_files/figure-html/thecode-1.png)
### Manage Dates Data with Base R
This section explains how to deal with date data in base R. It takes a [connected scatterplot](https://www.r-graph-gallery.com/connected-scatterplot.html) as an example and display several options to deal with dates.
#### Important note about the `lubridate()` library.
I strongly advise to have a look to the `lubridate()` library. It allows to easily manipulate the date format, and is very powerful in conjunction with [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html). Have a look to the [time series section](https://www.r-graph-gallery.com/time-series.html) of the gallery.
##### Is your date recognized as a date?
R offers a special data type for dates. It is important to use it since it will make the creation of charts lot easier. The `str()` function allows to check the type of each column. In the example beside, the `date` column is recognized as a factor.
```{r manage-dates-data-base-r, echo=TRUE, message=FALSE, warning=FALSE}
# Create data
set.seed(124)
date <- paste( "2015/03/" , sample(seq(1,31),6) , sep="")
value <- sample(seq(1,100) , 6)
data <- data.frame(date,value)
# Date and time are recognized as factor:
str(data)
```
#### Why it Matters
The issue is that your plot is gonna be very disappointing if the date is not recognized properly, as shown beside
```{r manage-dates-data-base-r-two, echo=TRUE, message=FALSE, warning=FALSE}
# Create data
set.seed(124)
date <- paste("2015/03/" , sample(seq(1,31),6) , sep="")
value <- sample(seq(1,100) , 6)
data <- data.frame(date,value)
# Date and time are recognized as factor:
str(data)
```
### Switch to Date Format
You can use the `as.Date()` function to specify that a column is at the date format. Now, with a bit of customization, we can get a nice [connected scatterplot](https://www.r-graph-gallery.com/connected-scatterplot.html) from our data:
```{r switch-dates-format-correlation, echo=TRUE, message=FALSE, warning=FALSE}
# Create data
set.seed(124)
date <- paste( "2015/03/" , sample(seq(1,31),6) , sep="")
value <- sample(seq(1,100) , 6)
data <- data.frame(date,value)
# Let's change the date to the "date" format:
data$date <- as.Date(data$date)
# So we can sort the table:
data <- data[order(data$date) , ]
# Easy to make it better now:
plot(data$value~data$date , type="b" , lwd=3 , col=rgb(0.1,0.7,0.1,0.8) , ylab="value of ..." , xlab="date" , bty="l" , pch=20 , cex=4)
abline(h=seq(0,100,10) , col="grey", lwd=0.8)
```
### Base R Graph Parameters: Cheatsheet
This section aims to remind the options offered to customize a graph in base R. Understand in a sec how to use `lwd`, `pch`, `type`, `lty`, `cex`, and more. Base R offers many option to customize the chart appearance.
Basically everthing is double with those few options:
* `cex`: shape size
* `lwd`: line width
* `col`: control colors
* `lty`: line type
* `pch`: marker shape
* `type`: link between dots
<u>Note</u>: visit the cheatsheet section for more.
```{r base-r-parameters, echo=TRUE, message=FALSE, warning=FALSE}
# initialization
par(mar=c(3,3,3,3))
num <- 0 ;
num1 <- 0
plot(0,0 , xlim=c(0,21) , ylim=c(0.5,6.5), col="white" , yaxt="n" , ylab="" , xlab="")
#fill the graph
for (i in seq(1,20)){
points(i,1 , pch=i , cex=3)
points(i,2 , col=i , pch=16 , cex=3)
points(i,3 , col="black" , pch=16 , cex=i*0.25)
#lty
if(i %in% c(seq(1,18,3))){
num=num+1
points(c(i,i+2), c(4,4) , col="black" , lty=num , type="l" , lwd=2)
text(i+1.1 , 4.15 , num)
}
#type and lwd
if(i %in% c(seq(1,20,5))){
num1=num1+1
points(c(i,i+1,i+2,i+3), c(5,5,5,5) , col="black" , type=c("p","l","b","o")[num1] , lwd=2)
text(i+1.1 , 5.2 , c("p","l","b","o")[num1] )
points(c(i,i+1,i+2,i+3), c(6,6,6,6) , col="black" , type="l", lwd=num1)
text(i+1.1 , 6.2 , num1 )
}
}
#add axis
axis(2, at = c(1,2,3,4,5,6), labels = c("pch" , "col" , "cex" , "lty", "type" , "lwd" ),
tick = TRUE, col = "black", las = 1, cex.axis = 0.8)
```
## Density 2D
---
A [2D density chart](https://www.data-to-viz.com/graph/density2d.html) displays the relationship between 2 numeric variables. One is represented on the X axis, the other on the Y axis, like for a [scatterplot](https://www.r-graph-gallery.com/scatterplot.html). Then, the number of observations within a particular area of the 2D space is counted and represented by a color gradient. Several types of 2d density chart exist:
#### 2d Histogram with `geom_bin2d()`
This is the two dimension version of the classic [histogram](https://www.r-graph-gallery.com/histogram.html). The plot area is split in a multitude of small squares, the number of points in each square is represented by its color.
### The Issue with `geom_point()`
A 2d density plot is useful to study the relationship between 2 numeric variables if you have a huge number of points. To avoid overlapping (as in the scatterplot beside), it divides the plot area in a multitude of small fragment and represents the number of points in this fragment. There are several types of 2d density plots. Each has its proper ggplot2 function. This section describes all of them.
```r
# Library
library(tidyverse)
# Data
a <- data.frame( x=rnorm(20000, 10, 1.9), y=rnorm(20000, 10, 1.2) )
b <- data.frame( x=rnorm(20000, 14.5, 1.9), y=rnorm(20000, 14.5, 1.9) )
c <- data.frame( x=rnorm(20000, 9.5, 1.9), y=rnorm(20000, 15.5, 1.9) )
data <- rbind(a,b,c)
# Basic scatterplot
ggplot(data, aes(x=x, y=y) ) +
geom_point()# 2d histogram with default option
ggplot(data, aes(x=x, y=y) ) +
geom_bin2d() +
theme_bw()
```
![](https://www.r-graph-gallery.com/2d-density-plot-with-ggplot2_files/figure-html/thecode-1.png)
### 2d Histogram with `geom_bin2d()`
This is the two dimension version of the classic [histogram](https://www.r-graph-gallery.com/histogram.html). The plot area is split in a multitude of small squares, the number of points in each square is represented by its color.
For 2d histogram, the plot area is divided in a multitude of squares. (It is a 2d version of the classic histogram). It is called using the `geom_bin_2d()` function. This function offers a bins argument that controls the number of `bins` you want to display.
<u>Note</u>: If you're not convinced about the importance of the `bins` option, read this.
```r
# 2d histogram with default option
ggplot(data, aes(x=x, y=y) ) +
geom_bin2d() +
theme_bw()
```
![](https://www.r-graph-gallery.com/2d-density-plot-with-ggplot2_files/figure-html/thecode2-1.png)
```r
# Bin size control + color palette
ggplot(data, aes(x=x, y=y) ) +
geom_bin2d(bins = 70) +
scale_fill_continuous(type = "viridis") +
theme_bw()
```
![](https://www.r-graph-gallery.com/2d-density-plot-with-ggplot2_files/figure-html/thecode2-2.png)
### Hexbin Chart with `geom_hex()`
Another alternative is to divide the plot area in a multitude of hexagons: it is thus called a hexbin chart, and is made using the `geom_hex()` function.
This function provides the `bins` argument as well, to control the number of division per axis.
```r
# Hexbin chart with default option
ggplot(data, aes(x=x, y=y) ) +
geom_hex() +
theme_bw()
```
![](https://www.r-graph-gallery.com/2d-density-plot-with-ggplot2_files/figure-html/thecode3-1.png)
```r
# Bin size control + color palette
ggplot(data, aes(x=x, y=y) ) +
geom_hex(bins = 70) +
scale_fill_continuous(type = "viridis") +
theme_bw()
```
![](https://www.r-graph-gallery.com/2d-density-plot-with-ggplot2_files/figure-html/thecode3-2.png)
### 2d Distribution with `geom_density_2d` or `stat_density_2d`
As you can plot a [density chart](https://www.r-graph-gallery.com/density-plot.html) instead of a [histogram](https://www.r-graph-gallery.com/histogram.html), it is possible to compute a 2d density and represent it. Several possibilities are offered by `ggplot2`: you can show the contour of the distribution, or the area, or use the `raster` function:
```r
# Show the contour only
ggplot(data, aes(x=x, y=y) ) +
geom_density_2d()
```
![](https://www.r-graph-gallery.com/2d-density-plot-with-ggplot2_files/figure-html/thecode4-1.png)
```r
# Show the area only
ggplot(data, aes(x=x, y=y) ) +
stat_density_2d(aes(fill = ..level..), geom = "polygon")
```
![](https://www.r-graph-gallery.com/2d-density-plot-with-ggplot2_files/figure-html/thecode4-2.png)
```r
# Area + contour
ggplot(data, aes(x=x, y=y) ) +
stat_density_2d(aes(fill = ..level..), geom = "polygon", colour="white")
```
![](https://www.r-graph-gallery.com/2d-density-plot-with-ggplot2_files/figure-html/thecode4-3.png)
```r
# Using raster
ggplot(data, aes(x=x, y=y) ) +
stat_density_2d(aes(fill = ..density..), geom = "raster", contour = FALSE) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
theme(
legend.position='none'
)
```
![](https://www.r-graph-gallery.com/2d-density-plot-with-ggplot2_files/figure-html/thecode4-4.png)
### Customize the Color Palette
Whatever you use a 2d histogram, a hexbin chart or a 2d distribution, you can and should custom the colour of your chart. Here is a suggestion using the `scale_fill_distiller()` function. You can see other methods in the [ggplot2 section](https://www.r-graph-gallery.com/ggplot2-package.html) of the gallery.
```r
# Call the palette with a number
ggplot(data, aes(x=x, y=y) ) +
stat_density_2d(aes(fill = ..density..), geom = "raster", contour = FALSE) +
scale_fill_distiller(palette=4, direction=-1) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
theme(
legend.position='none'
)
```
![](https://www.r-graph-gallery.com/2d-density-plot-with-ggplot2_files/figure-html/thecode5-1.png)
```r
# The direction argument allows to reverse the palette
ggplot(data, aes(x=x, y=y) ) +
stat_density_2d(aes(fill = ..density..), geom = "raster", contour = FALSE) +
scale_fill_distiller(palette=4, direction=1) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
theme(
legend.position='none'
)
```
![](https://www.r-graph-gallery.com/2d-density-plot-with-ggplot2_files/figure-html/thecode5-2.png)
```r
# You can also call the palette using a name.
ggplot(data, aes(x=x, y=y) ) +
stat_density_2d(aes(fill = ..density..), geom = "raster", contour = FALSE) +
scale_fill_distiller(palette= "Spectral", direction=1) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
theme(
legend.position='none'
)
```
![](https://www.r-graph-gallery.com/2d-density-plot-with-ggplot2_files/figure-html/thecode5-3.png)
### Hexbin Chart with the Hexbin Package
This section explains how to build a hexbin chart with R using the `hexbin` package. Hexbin chart is a [2d density chart](https://www.r-graph-gallery.com/2d-density-chart.html), allowing to visualize the relationship between 2 numeric variables.
[Scatterplots](https://www.r-graph-gallery.com/scatterplot.html) can get very hard to interpret when displaying large datasets, as points inevitably overplot and can't be individually discerned.
Binning can be though of as a two-dimensional [histogram](https://www.r-graph-gallery.com/histogram.html), where shades of the bins take the place of the heights of the bars. This technique is computed in the `hexbin` package.
This example has been published by [Myles Harrison](http://www.everydayanalytics.ca/2014/09/5-ways-to-do-2d-histograms-in-r.html) on R-bloggers.
```r
# Packages
library(hexbin)
library(RColorBrewer)
# Create data
x <- rnorm(mean=1.5, 5000)
y <- rnorm(mean=1.6, 5000)
# Make the plot
bin<-hexbin(x, y, xbins=40)
my_colors=colorRampPalette(rev(brewer.pal(11,'Spectral')))
plot(bin, main="" , colramp=my_colors , legend=F )
```
<center>
![](https://www.r-graph-gallery.com/100-high-density-scatterplot-with-binning_files/figure-html/thecode-1.png){width=75%}
</center>
### Hexbin Chart and Scatterplot with Ggplot2
This section explains how to build a hexbin chart with a [scatterplot](https://www.r-graph-gallery.com/scatterplot.html) on top using R and [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html). It is an addition to the page about [2d density plot with ggplot2](https://www.r-graph-gallery.com/2d-density-plot-with-ggplot2.html).
This plot extends the concepts described in the [2d density chart with ggplot2](https://www.r-graph-gallery.com/2d-density-plot-with-ggplot2.html) document. It simply illustrates that a [scatterplot](https://www.r-graph-gallery.com/scatterplot.html) can be added on top of the 2d density chart.
Thanks [Christian Jacob](http://chrisk91.me/) for this submission.
```{r hexbin-correlation-scatterplot-ggplot, echo=TRUE, message=FALSE, warning=FALSE}
# library
library(ggplot2)
# data
sample_data <- data.frame(x_values = 1:100 + rnorm(100,sd=20), y_values = 1:100 + rnorm(100,sd=27))
#plot
ggplot(sample_data, aes(x_values, y_values)) +
stat_density2d(geom="tile", aes(fill = ..density..), contour = FALSE) +
geom_point(colour = "white")
```
## Scatterplot
---
A [Scatterplot](https://www.r-graph-gallery.com/scatterplot.html) displays the relationship between 2 numeric variables. Each dot represents an observation. Their position on the X (horizontal) and Y (vertical) axis represents the values of the 2 variables.
#### Using the `ggplot2` Package
Scatterplots are built with [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html) thanks to the `geom_point()` function. Discover a basic use case in [graph #272](https://www.r-graph-gallery.com/272-basic-scatterplot-with-ggplot2.html), and learn how to custom it with next examples below. Basic scatterplot with R and ggplot2. A scatterplot displays the values of two variables along two axes. It shows the relationship between them, eventually revealing a correlation.
A [scatterplot](https://www.r-graph-gallery.com/scatterplot.html) displays the values of two variables along two axes. It shows the relationship between them, eventually revealing a correlation.
Here the relationship between Sepal width and Sepal length of several plants is shown.
It illustrates the basic utilization of `ggplot2` for scatterplots:
1. Provide a dataframe.
2. Tell which variable to show on x and y axis.
3. Add a `geom_point()` to show points.
```{r scatterplot-correlation-ggplot, echo=TRUE, message=FALSE, warning=FALSE}
# library
library(ggplot2)
# The iris dataset is provided natively by R
#head(iris)
# basic scatterplot
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
geom_point()
```
### Custom `ggplot2` Scatterplot
This post is dedicated to customization you can apply to a [scatterplot](https://www.r-graph-gallery.com/scatterplot.html) built with [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html).
This post follows the previous [basic scatterplot](https://www.r-graph-gallery.com/272-basic-scatterplot-with-ggplot2.html) with `ggplot2`. It shows the kind of customization you can apply to circles thanks to the `geom_point()` options:
* `color`: the stroke color, the circle outline
* `stroke`: the stroke width
fill: color of the circle inner part
* `shape`: shape of the marker. See list in the ggplot2 section
* `alpha`: circle transparency, [0->1], 0 is fully transparent
color: the stroke color, the circle outline
* `size`: circle size
<u>Note</u>: These options will be uniform among markers if you put it in the `geom_point()` call. You can also map them to a variable if put inside the `aes()` part of the code.
```{r scatterplot-correlation-ggplot-custom, echo=TRUE, message=FALSE, warning=FALSE}
# library
library(ggplot2)
# Iris dataset is natively provided by R
#head(iris)
# use options!
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
geom_point(
color="orange",
fill="#69b3a2",
shape=21,
alpha=0.5,
size=6,
stroke = 2
)
```
### Using `theme_ipsum`
Note that applying the `theme_ipsum` of the `hrbrthemes` package is always a good option.
```{r scatterplot-correlation-ggplot-ipsum, echo=TRUE, message=FALSE, warning=FALSE}
# library
library(ggplot2)
library(hrbrthemes)
# Iris dataset is natively provided by R
#head(iris)
# use options!
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
geom_point(
color="black",
fill="#69b3a2",
shape=22,
alpha=0.5,
size=6,
stroke = 1
) +
theme_ipsum()
```
### Map a Variable to Marker Feature in `ggplot2` Scatterplot
`ggplot2` allows to easily map a variable to marker features of a [scatterplot](https://www.r-graph-gallery.com/scatterplot.html). This section explaines how it works through several examples, with explanation and code.
#### Basic Example
Here is the magic of [ggplot2](https://www.r-graph-gallery.com/ggplot2): the ability to map a variable to marker features. Here, the marker `color` depends on its value in the field called `Species` in the input data frame.
Note that the legend is built automatically.
```{r scatterplot-correlation-map-variable, echo=TRUE, message=FALSE, warning=FALSE}
# load ggplot2
library(ggplot2)
library(hrbrthemes)
# mtcars dataset is natively available in R
# head(mtcars)
# A basic scatterplot with color depending on Species
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) +
geom_point(size=6) +
theme_ipsum()
```
### Works with any Aesthetics
Map variables to any marker features. For instance, specie is represente below using transparency (left), shape (middle) and size (right).
```{r scatterplot-correlation-aesthetics, echo=TRUE, message=FALSE, warning=FALSE}
# load ggplot2
library(ggplot2)
library(hrbrthemes)
# Transparency
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, alpha=Species)) +
geom_point(size=6, color="#69b3a2") +
theme_ipsum()
# Shape
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, shape=Species)) +
geom_point(size=6) +
theme_ipsum()
# Size
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, shape=Species)) +
geom_point(size=6) +
theme_ipsum()
```
### Mapping to Several Features
Last but not least, note that you can map one or several variables to one or several features. Here, shape, transparency, size and color all depends on the marker `Species` value.
```{r scatterplot-correlation-mapping-several-features, echo=TRUE, message=FALSE, warning=FALSE}
# load ggplot2
library(ggplot2)
library(hrbrthemes)
# A basic scatterplot with color depending on Species
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, shape=Species, alpha=Species, size=Species, color=Species)) +
geom_point() +
theme_ipsum()
```
### Add Text Labels with `ggplot2`
This document is dedicated to text annotation with [ggplot2](https://www.r-graph-gallery.com/ggplot2-package.html). It provides several examples with reproducible code showing how to use function like `geom_label` and `geom_text`.
#### Adding Text with `geom_text()`
This example demonstrates how to use `geom_text()` to add text as markers. It works pretty much the same as `geom_point()`, but add text instead of circles. A few arguments must be provided:
* `label`: What text you want to display.
* `nudge_x` and `nudge_y`: Shifts the text along X and Y axis.
* `check_overlap`: Tries to avoid text overlap. Note that a package called `ggrepel` extends this concept further.
```{r scatterplot-correlation-add-text-labels, echo=TRUE, message=FALSE, warning=FALSE}
# library
library(ggplot2)
# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)
# 1/ add text with geom_text, use nudge to nudge the text
ggplot(data, aes(x=wt, y=mpg)) +
geom_point() + # Show dots
geom_text(
label=rownames(data),
nudge_x = 0.25, nudge_y = 0.25,
check_overlap = T
)
```
### Add Labels with `geom_label()`
`geom_label()` works pretty much the same way as `geom_text()`. However, text is wrapped in a rectangle that you can customize (see next example).
```{r scatterplot-correlation-add-labels-geom, echo=TRUE, message=FALSE, warning=FALSE}
# library
library(ggplot2)
# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)
# 1/ add text with geom_text, use nudge to nudge the text
ggplot(data, aes(x=wt, y=mpg)) +
geom_point() + # Show dots
geom_label(
label=rownames(data),
nudge_x = 0.25, nudge_y = 0.25,
check_overlap = T
)
```
### Add One Text Label Only
Of course, you don't have to label all dots on the chart. You can also add a piece of text on a specific position. Since we're here, note that you can custom the annotation of `geom_label` with `label.padding`, `label.size`, `color` and `fill` as described below:
```{r scatterplot-correlation-add-one-text-only, echo=TRUE, message=FALSE, warning=FALSE}
# library
library(ggplot2)
# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)
# Add one annotation
ggplot(data, aes(x=wt, y=mpg)) +
geom_point() + # Show dots
geom_label(
label="Look at this!",
x=4.1,
y=20,
label.padding = unit(0.55, "lines"), # Rectangle size around label
label.size = 0.35,
color = "black",
fill="#69b3a2"
)
```
### Add Labels for a Selection of Marker
Last but not least, you can also select a group of marker and annotate them only. Here, only car with `mpg` > 20 and `wt` > 3 are annotated thanks to a data filtering in the `geom_label()` call.
```{r scatterplot-correlation-add-labels-selection-marker, echo=TRUE, message=FALSE, warning=FALSE}
# library
library(ggplot2)
library(dplyr)
library(tibble)
# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)
# Change data rownames as a real column called 'carName'
data <- data %>%
rownames_to_column(var="carName")
# Plot
ggplot(data, aes(x=wt, y=mpg)) +
geom_point() +
geom_label(
data=data %>% filter(mpg>20 & wt>3), # Filter data first
aes(label=carName)
)
```
### Ggplot2 Scatterplot with Rug
This section demonstrates how to build a [scatterplot](https://www.r-graph-gallery.com/scatterplot.html) with `rug` with `R` and `ggplot2`. Adding rug gives insight about variable distribution and is especially helpful when markers overlap.
#### Adding Rug with `geom_rug()`
A [scatterplot](https://www.r-graph-gallery.com/scatterplot.html) displays the relationship between 2 numeric variables. You can easily add rug on X and Y axis thanks to the `geom_rug()` function to illustrate the distribution of dots.
Note you can as well add [marginal plots](https://www.r-graph-gallery.com/277-marginal-histogram-for-ggplot2.html) to show these distributions.
```{r scatterplot-correlation-ggplot-scatter-rug, echo=TRUE, message=FALSE, warning=FALSE}
# library
library(ggplot2)
# Iris dataset
head(iris)
# plot
ggplot(data=iris, aes(x=Sepal.Length, Petal.Length)) +