using plotly to draw point,line,histogram ect

R
Author

Tony Duan

Published

July 10, 2023

Code
library(tidyverse)
library(plotly)
library(gapminder)
Code
data001=gapminder
head(data001)
# A tibble: 6 × 6
  country     continent  year lifeExp      pop gdpPercap
  <fct>       <fct>     <int>   <dbl>    <int>     <dbl>
1 Afghanistan Asia       1952    28.8  8425333      779.
2 Afghanistan Asia       1957    30.3  9240934      821.
3 Afghanistan Asia       1962    32.0 10267083      853.
4 Afghanistan Asia       1967    34.0 11537966      836.
5 Afghanistan Asia       1972    36.1 13079460      740.
6 Afghanistan Asia       1977    38.4 14880372      786.
Code
data002= data001 %>% filter(year==1997)

1 dot chart

plot_ly(data = data002, x = ~xxx, y = ~xxx, color =~xxx)

Code
plot_ly(data = data002, x = ~lifeExp, y = ~gdpPercap, color =~continent)
405060708005k10k15k20k25k30k35k40k
AfricaAmericasAsiaEuropeOceanialifeExpgdpPercap

2 line chart

Code
data002= data001 %>% group_by(continent,year) %>% summarise(pop=sum(pop)) 
Code
plot_ly(data = data002, x = ~year, y = ~pop, color =~continent,mode='lines')
1960197019801990200000.5B1B1.5B2B2.5B3B3.5B4B
AfricaAmericasAsiaEuropeOceaniayearpop

3 bar chart

Code
data002= data001 %>% filter(year==1997) %>% group_by(continent) %>% summarise(pop=sum(pop))
Code
plot_ly(data002, x = ~continent, y = ~pop, type = 'bar')
AfricaAmericasAsiaEuropeOceania00.5B1B1.5B2B2.5B3B3.5B
continentpop

4 histogram

Code
data002= data001 %>% filter(year==1997)
Code
plot_ly(data002,x = ~gdpPercap, type = "histogram",color = ~continent)
2.5k7.5k12.5k17.5k22.5k27.5k32.5k37.5k42.5k051015202530354045
AfricaAmericasAsiaEuropeOceaniagdpPercap

5 box plot

Code
data002= data001 %>% filter(year==1997)
Code
plot_ly(data002,x=~continent,y = ~gdpPercap, type = "box")
AfricaAmericasAsiaEuropeOceania05k10k15k20k25k30k35k40k
continentgdpPercap
Code
data002 %>% filter(continent=='Americas') %>% arrange(desc(gdpPercap)) %>% head()
# A tibble: 6 × 6
  country       continent  year lifeExp       pop gdpPercap
  <fct>         <fct>     <int>   <dbl>     <int>     <dbl>
1 United States Americas   1997    76.8 272911760    35767.
2 Canada        Americas   1997    78.6  30305843    28955.
3 Puerto Rico   Americas   1997    74.9   3759430    16999.
4 Argentina     Americas   1997    73.3  36203463    10967.
5 Venezuela     Americas   1997    72.1  22374398    10165.
6 Chile         Americas   1997    75.8  14599929    10118.

6 Reference

https://plotly.com/r/