这本书集中在静态图形-图像可以放置在论文,海报,幻灯片和期刊文章。通过与JavaScript库的连接,R还可以生成可放置在web页面上的交互式图形。
交互式图形超出了本书的范围。本章将指出一些最佳选项,以便您可以进一步研究它们。大多数使用htmlwidgets的R。
注意,如果你在iPad上阅读这篇文章,一些功能将不可用(如鼠标悬停)
Leaflet是用于交互式地图的JavaScript库。Leaflet包可用于生成Leaflet R图。
下面是一个简单的例子。点击图钉,用+/-按钮或鼠标滚轮放大或缩小,然后用手型光标拖动地图。
# create leaflet graph
library(leaflet)
leaflet() %>%
addTiles() %>%
addMarkers(lng=113.29,
lat=33.75,
popup="河南平顶山")
您可以创建点密度图和色谱图。软件包网站https://rstudio.github.io/leaflet/提供了详细的教程和大量示例。
Plotly是用于创建高端交互式可视化的商业服务和开源产品。plotly包允许您从R内创建图交互图。此外,任何ggplot2图都可以变成图。使用FuelEconomy“燃油经济性”数据,我们将创建一个交互式图表,显示按汽车类别划分的高速公路里程与发动机排量。将鼠标悬停在一个点上会显示有关该点的信息。单击图例点,从绘图中删除该类。再次单击它,将其返回。
library(tidyverse)
library(DT)
library(extrafont)
extrafont::choose_font(fonts = "Times New Roman") # 很好用的改变字体的包!
## [1] "Times New Roman"
mpg %>%
ggplot(aes(displ,hwy)) +
geom_point(aes(col = class),size = 3) +
labs(x = "Engine displacement",
y = "Highway Mileage",
color = "Car Class") +
theme(legend.title.align = 0.05,
plot.title = element_text(hjust = 0.5)) +
theme(text = element_text(family = "Times New Roman"))->p
p
plotly::ggplotly(p)
有很多关于plotly绘图信息的来源,参见R plotly和R的在线绘图书籍。 此外,DataCamp还提供免费的交互式教程。
rbokeh是Bokeh图形库的接口。我们将使用mtcars数据集创建另一个图表,显示发动机缸数与每加仑英里数的关系。鼠标移到,并尝试各种控件到图像的右边。
# prepare data
data(mtcars)
mtcars$name <- row.names(mtcars)
mtcars$cyl <- factor(mtcars$cyl)
library(rbokeh)
## Registered S3 method overwritten by 'pryr':
## method from
## print.bytes Rcpp
figure() %>%
ly_points(disp, mpg, data=mtcars,
color = cyl, glyph = cyl,
hover = list(name, mpg, wt))
## Warning in structure(x, class = unique(c("AsIs", oldClass(x)))): Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
## Consider 'structure(list(), *)' instead.
## Warning in structure(x, class = unique(c("AsIs", oldClass(x)))): Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
## Consider 'structure(list(), *)' instead.
## Warning in structure(x, class = unique(c("AsIs", oldClass(x)))): Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
## Consider 'structure(list(), *)' instead.
## Warning in structure(x, class = unique(c("AsIs", oldClass(x)))): Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
## Consider 'structure(list(), *)' instead.
## Warning in structure(x, class = unique(c("AsIs", oldClass(x)))): Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
## Consider 'structure(list(), *)' instead.
## Warning in structure(x, class = unique(c("AsIs", oldClass(x)))): Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
## Consider 'structure(list(), *)' instead.
## Warning in structure(x, class = unique(c("AsIs", oldClass(x)))): Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
## Consider 'structure(list(), *)' instead.
## Warning in structure(x, class = unique(c("AsIs", oldClass(x)))): Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
## Consider 'structure(list(), *)' instead.
## Warning in structure(x, class = unique(c("AsIs", oldClass(x)))): Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
## Consider 'structure(list(), *)' instead.
## Warning in structure(x, class = unique(c("AsIs", oldClass(x)))): Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
## Consider 'structure(list(), *)' instead.
## Warning in structure(x, class = unique(c("AsIs", oldClass(x)))): Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
## Consider 'structure(list(), *)' instead.
## Warning in structure(x, class = unique(c("AsIs", oldClass(x)))): Calling 'structure(NULL, *)' is deprecated, as NULL cannot have attributes.
## Consider 'structure(list(), *)' instead.
你可以用Bokeh创建一些非凡的图形。
rCharts可以创建各种交互式图形。在下面的示例中,创建了头发与眼睛颜色的条形图。尝试将鼠标悬停在栏上。 您可以在分组图和堆叠图之间进行交互选择,并通过眼睛颜色包括或排除个案。
# create interactive bar chart
library(rCharts)
##
## Attaching package: 'rCharts'
## The following object is masked from 'package:purrr':
##
## %||%
## The following object is masked from 'package:readr':
##
## read_file
hair_eye_male = subset(as.data.frame(HairEyeColor),
Sex == "Male")
n1 <- nPlot(Freq ~ Hair,
group = 'Eye',
data = hair_eye_male,
type = 'multiBarChart'
)
n1$set(width = 600)
n1$show('iframesrc', cdn=TRUE)
## <iframe srcdoc=' <!doctype HTML>
## <meta charset = 'utf-8'>
## <html>
## <head>
##
## <link rel='stylesheet' href='//cdnjs.cloudflare.com/ajax/libs/nvd3/1.1.15-beta/nv.d3.min.css'>
##
##
##
## <script src='//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js' type='text/javascript'></script>
##
## <script src='//d3js.org/d3.v3.min.js' type='text/javascript'></script>
##
## <script src='//cdnjs.cloudflare.com/ajax/libs/nvd3/1.1.15-beta/nv.d3.min.js' type='text/javascript'></script>
##
## <script src='//nvd3.org/assets/lib/fisheye.js' type='text/javascript'></script>
##
##
## <style>
## .rChart {
## display: block;
## margin-left: auto;
## margin-right: auto;
## width: 600px;
## height: 400px;
## }
## </style>
##
## </head>
## <body >
##
## <div id = 'chart186041c96627' class = 'rChart nvd3'></div>
## <script type='text/javascript'>
## $(document).ready(function(){
## drawchart186041c96627()
## });
## function drawchart186041c96627(){
## var opts = {
## "dom": "chart186041c96627",
## "width": 600,
## "height": 400,
## "x": "Hair",
## "y": "Freq",
## "group": "Eye",
## "type": "multiBarChart",
## "id": "chart186041c96627"
## },
## data = [
## {
## "Hair": "Black",
## "Eye": "Brown",
## "Sex": "Male",
## "Freq": 32
## },
## {
## "Hair": "Brown",
## "Eye": "Brown",
## "Sex": "Male",
## "Freq": 53
## },
## {
## "Hair": "Red",
## "Eye": "Brown",
## "Sex": "Male",
## "Freq": 10
## },
## {
## "Hair": "Blond",
## "Eye": "Brown",
## "Sex": "Male",
## "Freq": 3
## },
## {
## "Hair": "Black",
## "Eye": "Blue",
## "Sex": "Male",
## "Freq": 11
## },
## {
## "Hair": "Brown",
## "Eye": "Blue",
## "Sex": "Male",
## "Freq": 50
## },
## {
## "Hair": "Red",
## "Eye": "Blue",
## "Sex": "Male",
## "Freq": 10
## },
## {
## "Hair": "Blond",
## "Eye": "Blue",
## "Sex": "Male",
## "Freq": 30
## },
## {
## "Hair": "Black",
## "Eye": "Hazel",
## "Sex": "Male",
## "Freq": 10
## },
## {
## "Hair": "Brown",
## "Eye": "Hazel",
## "Sex": "Male",
## "Freq": 25
## },
## {
## "Hair": "Red",
## "Eye": "Hazel",
## "Sex": "Male",
## "Freq": 7
## },
## {
## "Hair": "Blond",
## "Eye": "Hazel",
## "Sex": "Male",
## "Freq": 5
## },
## {
## "Hair": "Black",
## "Eye": "Green",
## "Sex": "Male",
## "Freq": 3
## },
## {
## "Hair": "Brown",
## "Eye": "Green",
## "Sex": "Male",
## "Freq": 15
## },
## {
## "Hair": "Red",
## "Eye": "Green",
## "Sex": "Male",
## "Freq": 7
## },
## {
## "Hair": "Blond",
## "Eye": "Green",
## "Sex": "Male",
## "Freq": 8
## }
## ]
##
## if(!(opts.type==="pieChart" || opts.type==="sparklinePlus" || opts.type==="bulletChart")) {
## var data = d3.nest()
## .key(function(d){
## //return opts.group === undefined ? 'main' : d[opts.group]
## //instead of main would think a better default is opts.x
## return opts.group === undefined ? opts.y : d[opts.group];
## })
## .entries(data);
## }
##
## if (opts.disabled != undefined){
## data.map(function(d, i){
## d.disabled = opts.disabled[i]
## })
## }
##
## nv.addGraph(function() {
## var chart = nv.models[opts.type]()
## .width(opts.width)
## .height(opts.height)
##
## if (opts.type != "bulletChart"){
## chart
## .x(function(d) { return d[opts.x] })
## .y(function(d) { return d[opts.y] })
## }
##
##
##
##
##
##
##
##
##
##
## d3.select("#" + opts.id)
## .append('svg')
## .datum(data)
## .transition().duration(500)
## .call(chart);
##
## nv.utils.windowResize(chart.update);
## return chart;
## });
## };
## </script>
##
## <script></script>
## </body>
## </html> ' scrolling='no' frameBorder='0' seamless class='rChart nvd3 ' id='iframe-chart186041c96627'> </iframe>
## <style>iframe.rChart{ width: 100%; height: 400px;}</style>
highcharter包提供对Highcharts JavaScript图形库的访问。这个包对非商业用途是免费的。 让我们使用highcharter创建一个交互式折线图,显示几个亚洲国家的预期寿命随时间的变化。数据来自Gapminder数据集。同样,将鼠标移到这些行上并尝试单击图例名称。
# create interactive line chart
library(highcharter)
## Highcharts (www.highcharts.com) is a Highsoft software product which is
## not free for commercial and Governmental use
# prepare data
data(gapminder, package = "gapminder")
library(dplyr)
asia <- gapminder %>%
filter(continent == "Asia") %>%
select(year, country, lifeExp)
# convert to long to wide format
library(tidyr)
plotdata <- spread(asia, country, lifeExp)
# generate graph
h <- highchart() %>%
hc_xAxis(categories = plotdata$year) %>%
hc_add_series(name = "Afghanistan",
data = plotdata$Afghanistan) %>%
hc_add_series(name = "Bahrain",
data = plotdata$Bahrain) %>%
hc_add_series(name = "Cambodia",
data = plotdata$Cambodia) %>%
hc_add_series(name = "China",
data = plotdata$China) %>%
hc_add_series(name = "India",
data = plotdata$India) %>%
hc_add_series(name = "Iran",
data = plotdata$Iran)
h
与本章中的所有交互式图形一样,有一些选项允许自定义图形。
# customize interactive line chart
h <- h %>%
hc_title(text = "Life Expectancy by Country",
margin = 20,
align = "left",
style = list(color = "steelblue")) %>%
hc_subtitle(text = "1952 to 2007",
align = "left",
style = list(color = "#2b908f",
fontWeight = "bold")) %>%
hc_credits(enabled = TRUE, # add credits
text = "Gapminder Data",
href = "http://gapminder.com") %>%
hc_legend(align = "left",
verticalAlign = "top",
layout = "vertical",
x = 0,
y = 100) %>%
hc_tooltip(crosshairs = TRUE,
backgroundColor = "#FCFFC5",
shared = TRUE,
borderWidth = 4) %>%
hc_exporting(enabled = TRUE)
h
通过R和JavaScript的结合,可以获得大量的交互图。选择适合你的方法。