rm(list = ls()); gc()
## used (Mb) gc trigger (Mb) max used (Mb)
## Ncells 530772 28.4 1205827 64.4 621328 33.2
## Vcells 996965 7.7 8388608 64.0 1600722 12.3
library(ggplot2)
library(dplyr) # %>% 符號
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(SportsAnalytics) # NBA球員資料
## Warning: package 'SportsAnalytics' was built under R version 3.6.3
NBA1516 <- fetch_NBAPlayerStatistics("15-16")
e.g. NBA球員不同位置FieldGoalsAttempted與TotalPoints點圖:
# colnames(NBA1516)
qplot(FieldGoalsAttempted, TotalPoints, data = NBA1516,
color = Position)
NBA1516 %>% ggplot(aes(x = FieldGoalsAttempted,
y = TotalPoints,
color = Position)) + geom_point()
qplot(FieldGoalsAttempted, TotalPoints, data = NBA1516,
color = Position,
geom = c("point", "smooth"))
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
#facets = . ~ Position 用守備位置Position分群畫圖(橫向)
qplot(FieldGoalsAttempted, TotalPoints, data = NBA1516,
facets = . ~ Position)
qplot(TotalPoints, data = NBA1516, fill = Position,
bins = 80)
colnames(NBA1516)
## [1] "League" "Name" "Team"
## [4] "Position" "GamesPlayed" "TotalMinutesPlayed"
## [7] "FieldGoalsMade" "FieldGoalsAttempted" "ThreesMade"
## [10] "ThreesAttempted" "FreeThrowsMade" "FreeThrowsAttempted"
## [13] "OffensiveRebounds" "TotalRebounds" "Assists"
## [16] "Steals" "Turnovers" "Blocks"
## [19] "PersonalFouls" "Disqualifications" "TotalPoints"
## [22] "Technicals" "Ejections" "FlagrantFouls"
## [25] "GamesStarted"
NBA1516 %>% mutate(ThreepointAcu = ThreesMade/ThreesAttempted) %>% ggplot() + geom_boxplot(aes(x = Team ,y = ThreepointAcu))
## Warning: Removed 42 rows containing non-finite values (stat_boxplot).
NBA1516 %>% group_by(Position) %>%
summarise(count = n()) %>%
ggplot(aes(x = Position, y = count)) +
geom_bar(stat = "identity")
## Warning: Factor `Position` contains implicit NA, consider using
## `forcats::fct_explicit_na`
NBA1516 %>% group_by(Team,Position) %>% summarise(totalThree = sum(ThreesMade)) %>% arrange(desc(totalThree)) %>%
ggplot() + geom_tile(aes(x = Position, y = Team,
fill = totalThree,
color = "white")) +
scale_fill_gradient(low = "white", high = "steelblue")
## Warning: Factor `Position` contains implicit NA, consider using
## `forcats::fct_explicit_na`
NBA1516 %>% group_by(Team,Position) %>% summarise(totalThree = sum(ThreesMade)) %>% arrange(desc(totalThree))
## Warning: Factor `Position` contains implicit NA, consider using
## `forcats::fct_explicit_na`
Choropleth map面量圖是指把統計資料用顏色畫在對應的地圖上的一種資料視覺化方式,在R中可以使用choroplethr(Lamstein 2018) package來畫面量圖, choroplethr package是一個基於ggplot2 package的面量圖做圖工具,使用前需要先安裝,建議同時安裝choroplethrMaps package
# install.packages(c("choroplethr","choroplethrMaps"))
library(choroplethr)
## Warning: package 'choroplethr' was built under R version 3.6.3
## Loading required package: acs
## Warning: package 'acs' was built under R version 3.6.3
## Loading required package: stringr
## Loading required package: XML
##
## Attaching package: 'acs'
## The following object is masked from 'package:dplyr':
##
## combine
## The following object is masked from 'package:base':
##
## apply
data(df_pop_state)
data(continental_us_states)
state_choropleth(df_pop_state,
title = "US 2012 State Population Estimates",
legend = "Population",
zoom = continental_us_states,
reference_map = FALSE)
# install.packages("devtools")
library(devtools)
## Warning: package 'devtools' was built under R version 3.6.3
## Loading required package: usethis
# install_github("wilkox/ggfittext") wrong!
# install_github("wilkox/treemapify") wrong!
# install.packages("treemapify") successful!
library(treemapify)
## Warning: package 'treemapify' was built under R version 3.6.3
data(G20)#載入範例資料
ggplot(G20, aes(area = gdp_mil_usd, fill = hdi, label = country)) + geom_treemap() +
scale_fill_gradient(low = "white",high = "steelblue") +
geom_treemap_text(fontface = "italic", colour = "black", place = "centre",grow = TRUE)
# install.packages("treemap")
library(treemap)
## Warning: package 'treemap' was built under R version 3.6.3
treemap(G20,
index = c("econ_classification","country"), #分組依據
vSize = "gdp_mil_usd", #區塊大小
vColor = "hdi", #顏色深淺
type = "value")
# install.packages("ggvis")
library(ggvis)
## Warning: package 'ggvis' was built under R version 3.6.3
##
## Attaching package: 'ggvis'
## The following object is masked from 'package:ggplot2':
##
## resolution
g <- ggvis(G20, x = ~ gdp_mil_usd, y = ~ hdi)
layer_points(g)
g <- ggvis(G20, x = ~ hdi)
layer_histograms(g,
width = input_slider(0, 2, step = 0.10, label = "width"),
center = input_slider(0, 2, step = 0.5, label = "center"))
## Warning: Can't output dynamic/interactive ggvis plots in a knitr document.
## Generating a static (non-dynamic, non-interactive) version of the plot.
除了input_slider()外,ggvis還提供以下互動式輸入介面: >input_checkbox() input_checkboxgroup() input_numeric() input_radiobuttons() input_select() input_text()
參考 官網
# install.packages("googleVis")
library(googleVis)
## Warning: package 'googleVis' was built under R version 3.6.3
## Creating a generic function for 'toJSON' from package 'jsonlite' in package 'googleVis'
##
## Welcome to googleVis version 0.6.4
##
## Please read Google's Terms of Use
## before you start using the package:
## https://developers.google.com/terms/
##
## Note, the plot method of googleVis will by default use
## the standard browser to display its output.
##
## See the googleVis package vignettes for more details,
## or visit https://github.com/mages/googleVis.
##
## To suppress this message use:
## suppressPackageStartupMessages(library(googleVis))
demo(googleVis)
##
##
## demo(googleVis)
## ---- ~~~~~~~~~
##
## > ## ---- googleVis demo ----
## > ## ---- pauseFunction ----
## > pause <- function(){
## + invisible(readline("\nPress <return> to continue: "))
## + }
##
## > ## ---- testData ----
## > df=data.frame(country=c("US", "GB", "BR"),
## + val1=c(10,13,14),
## + val2=c(23,12,32))
##
## > ## ---- LineChart ----
## > Line <- gvisLineChart(df)
##
## > plot(Line)
## starting httpd help server ...
## done
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- TwoAxis ----
## > Line2 <- gvisLineChart(df, "country", c("val1","val2"),
## + options=list(
## + series="[{targetAxisIndex: 0},
## + {targetAxisIndex:1}]",
## + vAxes="[{title:'val1'}, {title:'val2'}]"
## + ))
##
## > plot(Line2)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- SettingOptions ----
## > Line3 <- gvisLineChart(df, xvar="country", yvar=c("val1","val2"),
## + options=list(
## + title="Hello World",
## + titleTextStyle="{color:'red',
## + fontName:'Courier',
## + fontSize:16}",
## + backgroundColor="#D3D3D3",
## + vAxis="{gridlines:{color:'red', count:3}}",
## + hAxis="{title:'Country', titleTextStyle:{color:'blue'}}",
## + series="[{color:'green', targetAxisIndex: 0},
## + {color: 'orange',targetAxisIndex:1}]",
## + vAxes="[{title:'val1'}, {title:'val2'}]",
## + legend="bottom",
## + curveType="function",
## + width=500,
## + height=300
## + ))
##
## > plot(Line3)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- CustomizingLines ----
## > Dashed <- gvisLineChart(df, xvar="country", yvar=c("val1","val2"),
## + options=list(
## + series="[{color:'green', targetAxisIndex: 0,
## + lineWidth: 1, lineDashStyle: [2, 2, 20, 2, 20, 2]},
## + {color: 'blue',targetAxisIndex: 1,
## + lineWidth: 2, lineDashStyle: [4, 1]}]",
## + vAxes="[{title:'val1'}, {title:'val2'}]"
## + ))
##
## > plot(Dashed)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- EditButton ----
## > Line4 <- gvisLineChart(df, "country", c("val1","val2"),
## + options=list(gvis.editor="Edit me!"))
##
## > plot(Line4)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- BarChart ----
## > Bar <- gvisBarChart(df)
##
## > plot(Bar)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- ColumnChart ----
## > Column <- gvisColumnChart(df)
##
## > plot(Column)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- AreaChart ----
## > Area <- gvisAreaChart(df)
##
## > plot(Area)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- SteppedAreaChart ----
## > SteppedArea <- gvisSteppedAreaChart(df, xvar="country",
## + yvar=c("val1", "val2"),
## + options=list(isStacked=TRUE))
##
## > plot(SteppedArea)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- ComboChart ----
## > Combo <- gvisComboChart(df, xvar="country",
## + yvar=c("val1", "val2"),
## + options=list(seriesType="bars",
## + series='{1: {type:"line"}}'))
##
## > plot(Combo)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- ScatterChart ----
## > Scatter <- gvisScatterChart(women,
## + options=list(
## + legend="none",
## + lineWidth=2, pointSize=0,
## + title="Women", vAxis="{title:'weight (lbs)'}",
## + hAxis="{title:'height (in)'}",
## + width=300, height=300))
##
## > plot(Scatter)
##
## > ## ---- ScatterChartPoints ----
## > M <- matrix(nrow=6,ncol=6)
##
## > M[col(M)==row(M)] <- 1:6
##
## > dat <- data.frame(X=1:6, M)
##
## > SC <- gvisScatterChart(dat,
## + options=list(
## + title="Customizing points",
## + legend="right",
## + pointSize=30,
## + series="{
## + 0: { pointShape: 'circle' },
## + 1: { pointShape: 'triangle' },
## + 2: { pointShape: 'square' },
## + 3: { pointShape: 'diamond' },
## + 4: { pointShape: 'star' },
## + 5: { pointShape: 'polygon' }
## + }"))
##
## > plot(SC)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- BubbleChart ----
## > Bubble <- gvisBubbleChart(Fruits, idvar="Fruit",
## + xvar="Sales", yvar="Expenses",
## + colorvar="Year", sizevar="Profit",
## + options=list(
## + hAxis='{minValue:75, maxValue:125}'))
##
## > plot(Bubble)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- CandlestickChart ----
## > Candle <- gvisCandlestickChart(OpenClose,
## + options=list(legend='none'))
##
## > plot(Candle)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- PieChart ----
## > Pie <- gvisPieChart(CityPopularity)
##
## > plot(Pie)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- Gauge ----
## > Gauge <- gvisGauge(CityPopularity,
## + options=list(min=0, max=800, greenFrom=500,
## + greenTo=800, yellowFrom=300, yellowTo=500,
## + redFrom=0, redTo=300, width=400, height=300))
##
## > plot(Gauge)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- IntensityMap ----
## > Intensity <- gvisIntensityMap(df)
##
## > plot(Intensity)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- GeoChart ----
## > Geo=gvisGeoChart(Exports, locationvar="Country",
## + colorvar="Profit",
## + options=list(projection="kavrayskiy-vii"))
##
## > plot(Geo)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- USStateData ----
## > require(datasets)
##
## > states <- data.frame(state.name, state.x77)
##
## > GeoStates <- gvisGeoChart(states, "state.name", "Illiteracy",
## + options=list(region="US",
## + displayMode="regions",
## + resolution="provinces",
## + width=600, height=400))
##
## > plot(GeoStates)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- GeoChartHurricaneAndrew ----
## > GeoMarker <- gvisGeoChart(Andrew, "LatLong",
## + sizevar='Speed_kt',
## + colorvar="Pressure_mb",
## + options=list(region="US"))
##
## > plot(GeoMarker)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- GoogleMapHurricaneAndrew ----
## > AndrewMap <- gvisMap(Andrew, "LatLong" , "Tip",
## + options=list(showTip=TRUE,
## + showLine=TRUE,
## + enableScrollWheel=TRUE,
## + mapType='terrain',
## + useMapTypeControl=TRUE))
##
## > plot(AndrewMap)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- Table ----
## > Table <- gvisTable(Stock,
## + formats=list(Value="#,###"))
##
## > plot(Table)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- TableWithPages ----
## > PopTable <- gvisTable(Population,
## + formats=list(Population="#,###",
## + '% of World Population'='#.#%'),
## + options=list(page='enable'))
##
## > plot(PopTable)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- OrgChart ----
## > Org <- gvisOrgChart(Regions,
## + options=list(width=600, height=250,
## + size='large', allowCollapse=TRUE))
##
## > plot(Org)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- TreeMap ----
## > Tree <- gvisTreeMap(Regions,
## + "Region", "Parent",
## + "Val", "Fac",
## + options=list(fontSize=16))
##
## > plot(Tree)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- AnnotationChart ----
## > Anno <- gvisAnnotationChart(Stock,
## + datevar="Date",
## + numvar="Value",
## + idvar="Device",
## + titlevar="Title",
## + annotationvar="Annotation",
## + options=list(
## + width=600, height=350,
## + fill=10, displayExactValues=TRUE,
## + colors="['#0000ff','#00ff00']")
## + )
##
## > plot(Anno)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- SankeyChart ----
## > datSK <- data.frame(From=c(rep("A",3), rep("B", 3)),
## + To=c(rep(c("X", "Y", "Z"),2)),
## + Weight=c(5,7,6,2,9,4))
##
## > Sankey <- gvisSankey(datSK, from="From", to="To", weight="Weight",
## + options=list(
## + sankey="{link: {color: { fill: '#d799ae' } },
## + node: { color: { fill: '#a61d4c' },
## + label: { color: '#871b47' } }}"))
##
## > plot(Sankey)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > # ---- CalendarChart ----
## > Cal <- gvisCalendar(Cairo,
## + datevar="Date",
## + numvar="Temp",
## + options=list(
## + title="Daily temperature in Cairo",
## + height=320,
## + calendar="{yearLabel: { fontName: 'Times-Roman',
## + fontSize: 32, color: '#1A8763', bold: true},
## + cellSize: 10,
## + cellColor: { stroke: 'red', strokeOpacity: 0.2 },
## + focusedCellColor: {stroke:'red'}}")
## + )
##
## > plot(Cal)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > # ---- Timeline ----
## > datTL <- data.frame(Position=c(rep("President", 3), rep("Vice", 3)),
## + Name=c("Washington", "Adams", "Jefferson",
## + "Adams", "Jefferson", "Burr"),
## + start=as.Date(x=rep(c("1789-03-29", "1797-02-03",
## + "1801-02-03"),2)),
## + end=as.Date(x=rep(c("1797-02-03", "1801-02-03",
## + "1809-02-03"),2)))
##
## > Timeline <- gvisTimeline(data=datTL,
## + rowlabel="Name",
## + barlabel="Position",
## + start="start",
## + end="end",
## + options=list(timeline="{groupByRowLabel:false}",
## + backgroundColor='#ffd',
## + height=350,
## + colors="['#cbb69d', '#603913', '#c69c6e']"))
##
## > plot(Timeline)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- Histogram ----
## > set.seed(123)
##
## > datHist=data.frame(A=rpois(100, 20),
## + B=rpois(100, 5),
## + C=rpois(100, 50))
##
## > Hist <- gvisHistogram(datHist, options=list(
## + legend="{ position: 'top', maxLines: 2 }",
## + colors="['#5C3292', '#1A8763', '#871B47']",
## + width=400, height=360))
##
## > plot(Hist)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- WordTree ----
## > wt1 <- gvisWordTree(Cats, textvar = "Phrase")
##
## > plot(wt1)
##
## > ## ---- gvisMerge ----
## > G <- gvisGeoChart(Exports, "Country", "Profit",
## + options=list(width=300, height=300))
##
## > T <- gvisTable(Exports,
## + options=list(width=220, height=300))
##
## > GT <- gvisMerge(G,T, horizontal=TRUE)
##
## > plot(GT)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## Flash charts
## > ## ---- GeoMap ----
## > Geo=gvisGeoMap(Exports, locationvar="Country", numvar="Profit",
## + options=list(height=350, dataMode='regions'))
## Warning in gvisGeoMap(Exports, locationvar = "Country", numvar = "Profit", : GeoMap (gvisGeoMap) is Flash based, conisder using GeoChart (gvisGeoChart) instead.
## For more details visit: goo.gl/tkiEV8
##
## > plot(Geo)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- GeoMap ----
## > AndrewGeo <- gvisGeoMap(Andrew,
## + locationvar="LatLong",
## + numvar="Speed_kt",
## + hovervar="Category",
## + options=list(height=350,
## + region="US",
## + dataMode="markers"))
## Warning in gvisGeoMap(Andrew, locationvar = "LatLong", numvar = "Speed_kt", : GeoMap (gvisGeoMap) is Flash based, conisder using GeoChart (gvisGeoChart) instead.
## For more details visit: goo.gl/tkiEV8
##
## > plot(AndrewGeo)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- AnnotatedTimeLine ----
## > AnnoTimeLine <- gvisAnnotatedTimeLine(Stock,
## + datevar="Date",
## + numvar="Value",
## + idvar="Device",
## + titlevar="Title",
## + annotationvar="Annotation",
## + options=list(displayAnnotations=TRUE,
## + width="600px", height="350px"))
## Warning in gvisAnnotatedTimeLine(Stock, datevar = "Date", numvar = "Value", : AnnotatedTimeline (gvisAnnotatedTimeLine) is Flash based, conisder using AnnotationChart (gvisAnnotationChart) instead.
## For more details visit: goo.gl/tkiEV8
##
## > plot(AnnoTimeLine)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## ---- MotionChart ----
## > Motion=gvisMotionChart(Fruits,
## + idvar="Fruit",
## + timevar="Year")
##
## > plot(Motion)
##
## > ## ---- pause ----
## > pause()
##
## Press <return> to continue:
##
## > ## You can change some of displaying settings via the browser,
## > ## e.g. the level of opacity of non-selected items, or the chart type.
## > ## The state string from the 'Advanced' tab can be used to set those
## > ## settings via R. Just copy and past the string from the browser into
## > ## the argument state of the options list.
## > ## Here is an example of a motion chart, with an initial line chart
## > ## displayed.
## >
## > ## ---- MotionChartSettings ----
## > myStateSettings <-'
## + {"xZoomedDataMin":1199145600000,"colorOption":"2",
## + "duration":{"timeUnit":"Y","multiplier":1},"yLambda":1,
## + "yAxisOption":"4","sizeOption":"_UNISIZE",
## + "iconKeySettings":[],"xLambda":1,"nonSelectedAlpha":0,
## + "xZoomedDataMax":1262304000000,"iconType":"LINE",
## + "dimensions":{"iconDimensions":["dim0"]},
## + "showTrails":false,"uniColorForNonSelected":false,
## + "xAxisOption":"_TIME","orderedByX":false,"playDuration":15000,
## + "xZoomedIn":false,"time":"2010","yZoomedDataMin":0,
## + "yZoomedIn":false,"orderedByY":false,"yZoomedDataMax":100}
## + '
##
## > M <- gvisMotionChart(Fruits, "Fruit", "Year", options=list(state=myStateSettings))
##
## > plot(M)
##
## > ## See demo(package='googleVis') for other available demos.
require(datasets) # data: state
states <- data.frame(state.name, state.x77)
GeoStates <- gvisGeoChart(states, "state.name", "Illiteracy",
# Illiteracy 文盲(比率)
options=list(region="US",
displayMode="regions",
resolution="provinces",
width=600, height=400))
plot(GeoStates)
# 1992/8/16 - 8/28安德魯颶風路徑
AndrewMap <- gvisMap(Andrew, "LatLong" , "Tip",
# LatLong 緯/經度
options=list(showTip=TRUE,
showLine=TRUE,
enableScrollWheel=TRUE,
mapType='terrain',
useMapTypeControl=TRUE))
plot(AndrewMap)
# install.packages("plotly")
library(plotly)
## Warning: package 'plotly' was built under R version 3.6.3
##
## Attaching package: 'plotly'
## The following objects are masked from 'package:ggvis':
##
## add_data, hide_legend
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
# 鑽石的價格與其他屬性之數據
d <- diamonds[sample(nrow(diamonds), 1000), ]
p <- ggplot(data = d, aes(x = carat, y = price)) +
geom_point(aes(text = paste("Clarity:", clarity))) +
geom_smooth(aes(colour = cut, fill = cut)) + facet_wrap(~ cut)
## Warning: Ignoring unknown aesthetics: text
ggplotly(p)
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'