R可视化绘图三-recharts

更新

http://blog.csdn.net/q383700092/article/details/53410845

-------------------

recharts

安装  win7 成功
library(RCurl)
library(httr)
library(htmltools)
安装Rtools
install.packages('devtools')
library(devtools)
install_github('yihui/recharts')

ubuntu下安装R包出错  最后成功
ERROR: configuration failed for package ‘RCurl’
installation of package ‘RCurl’ had non-zero exit status
ubuntu下安装
apt-get -y build-dep libcurl4-gnutls-dev
apt-get -y install libcurl4-gnutls-dev
R安装
install.packages('devtools')
library(devtools)
install_github('yihui/recharts')
echartR的主要工作是将Echarts参数封装成list,Yihui Xie的原型函数echart被用来处理这个list
散点图
library(recharts)
#data x y
echart(iris, ~Sepal.Length, ~Sepal.Width)
#data x y 分类
echart(iris, ~Sepal.Length, ~Sepal.Width, series = ~Species)
默认地址C:\Users\lenovo\AppData\Local\Temp\RtmpgxDGJ9\viewhtml185c70384e91(后面会有区别,根据最后修改时间找出html)
echartR则主要细化了部分参数的设置方法
下载 Download  echartR.R脚本文件到本地位置
调用 Source  echartR 脚本
source("~/Github/recharts/R/echartR.R")
source("echartR.R")
语法--详细可参看网页http://blog.sina.com.cn/s/blog_6cd6c0510102vsp1.html  http://madlogos.github.io/recharts/files/echartR.html

例子
rm(list=ls())
#设置全局变量
library(recharts)
Sys.setlocale("LC_CTYPE","Chs")
source("echartR.R")
knitr::opts_chunk$set(message=FALSE,warning=FALSE,results='asis')
简单加载全局变量
library(recharts)
source('echartR.R')
单系列散点图type = 'scatter'--均数线(markLine=c(1,NA,'average',F))--palette: 调色板solarized_magenta腮红色 --scatter:散点
echartR(data = iris, x = ~Sepal.Width, y = ~Petal.Width, 
        type = 'scatter', palette='solarized_magenta',
        title = '单系列散点图', 
        subtitle = "小标题", xlab = 'Sepal Width', ylab = 'Petal Width',
        markLine=t(c(1,'Mean',"average",F)))
简化版
echartR(iris,~Sepal.Width,~Petal.Width,type = 'scatter')
多系列散点图--symbolList: 图形标志-circle圆圈
echartR(data = iris, x = ~Sepal.Width, y = ~Petal.Width, series = ~Species,
        type = 'scatter', palette='wsj_dem_rep', symbolList='circle',
        scale=F, xAxis = list(lab='Sepal Width', color='darkgray'),
        yAxis = list(lab='Petal Width',color='none'),
        title = 'Scatter - Sepal Width vs Petal Width, by Species',
        subtitle ='(source: iris)', 
        markLine=rbind(c(2,'Mean','average',F),c('versicolor','Maximum','max',F),
                       c(2,'Minimum','min',F)),
        markPoint=rbind(c(1,'Max','max',F),c(2,'Min','min',F), c(3,'Max','max',T)))
简化版

echartR(data = iris, x = ~Sepal.Width, y = ~Petal.Width,series = ~Species, type = 'scatter')

R可视化绘图三-recharts_第1张图片

R可视化绘图三-recharts_第2张图片

拟合线+散点图-同时拟合3条回归线(markLine列表写作short form,类型指定为’lm’,并开启炫光特效)。
随机选择excel_old色版中的1种颜色
echartR(data = iris, x = ~Sepal.Width, y = ~Petal.Width, series = ~Species,
        type = 'scatter', palette='excel_old(1)',
        symbolList=c('arrow','heart','star8'),
        title = 'Scatter - Sepal Width vs Petal Width, by Species',
        subtitle = '(source: iris)', xlab = 'Sepal Width', ylab = 'Petal Width',
        markLine = rbind(c('setosa','Linear Reg Coef','lm',T), 
                         c(2,'Linear Reg Coef','lm',T), c(3,'Linear Reg Coef','lm',T)))
散点图-大规模散点图(2000个点以上)同样可以秒级出图(但html文件会变得很大)。
x <- rnorm(2001)*2
e <- vector()
for (i in 1:2001)  e <- c(e,rnorm(1,0,x[i]+abs(min(x))))
df <- data.frame(x, sin=sin(x)+e/20, cos=cos(x)+e/20)
df <- melt(df,id="x")
echartR(df,x=~x,y=~value,series=~variable,type='scatter',
        palette='wsj_red_green',symbolList='circle', AxisAtZero=F,
        title='Scatter of 2,001 points', subtitle = 'Large-scale scatter')  
气泡图type = 'bubble'--与散点图类似-type改为bubble即可,如不指定weight变量,函数默认指定y为气泡权重
单系列气泡图
echartR(data = iris, x = ~Sepal.Width, y = ~Petal.Width, weight = ~Petal.Length,
        type = 'bubble', palette='solarized_cyan',
        title = paste("Bubble - Sepal Width vs Petal Width,",
                      "weighed by Petal Length"),
        subtitle = '(source: iris)',
        xlab = 'Sepal Width', ylab = 'Petal Width')
简化版
echartR(iris, ~Sepal.Width, ~Petal.Width,weight = ~Petal.Length,type = 'bubble')
多系列气泡图--palette设置为tableauGnOr(3),只随机取该色板的3种颜色--基于全集的线性回归(lm())
fit <- lm(Petal.Width~Sepal.Width,iris)
pred <- data.frame(Sepal.Width=c(min(iris$Sepal.Width),max(iris$Sepal.Width)))
yhat <- round(predict(fit,pred),2)
echartR(data = iris, x = ~Sepal.Width, y = ~Petal.Width, 
        weight = ~Petal.Length, series = ~Species, 
        symbolList=c('emptyCircle','circle'), 
        type = 'bubble', palette='tableaugnor(4)',
        title = paste('Bubble - Sepal Width vs Petal Width, by Species,',
                      'weighed by Petal Length'), 
        subtitle = '(source: iris)', xlab = 'Sepal Width', ylab = 'Petal Width',
        markLine=t(c('Reg Coef.','slope',round(fit$coefficients[[2]],2), 
                     pred[1,1],yhat[[1]],pred[2,1],yhat[[2]],F))
简化版
echartR(iris, ~Sepal.Width, ~Petal.Width,weight = ~Petal.Length,series = ~Species,symbolList=c('emptyCircle','circle'), type = 'bubble')
柱图-柱状图 type = 'bar'
#生成数据
library(reshape2)
dfiris <- iris
dfiris$id <- row.names(iris)
dfiris <- melt(dfiris,id=c("Species","id"))
names(dfiris) <- c("Species","id","Param","Value")
dtiris <- dcast(dfiris[,c(1,3,4)],Species+Param~.,value.var="Value",mean)
names(dtiris) <- c("Species","Param","Mean")
knitr::kable(dcast(dtiris,Param~Species,sum,value.var="Mean"),
             format='html',caption="Table: Mean of parameters (iris)")
#绘制柱状图  
echartR(data = dtiris, x = ~Param, y = ~Mean,  series = ~Species,
        type = 'bar', palette='fivethirtyeight',
        title = "Column - Parameter Mean by Species", 
        subtitle = '(source: iris)',legend_pos=3,
        xlab = 'Parameter', ylab = 'Mean')
简化版

echartR(data = dtiris, x = ~Param, y = ~Mean,  series = ~Species,type = 'bar')

R可视化绘图三-recharts_第3张图片

堆积柱图 stack=T
echartR(data = dtiris, x = ~Param, y = ~Mean, 
        series = ~Species, stack=T,
        type = 'bar', palette='pander',
        title = "Column - Parameter Mean by Species",
        subtitle = '(source: iris)',
        xlab = 'Parameter', ylab = 'Mean', legend_pos=3)
简化版
echartR(data = dtiris, x = ~Param, y = ~Mean,  series = ~Species,type = 'bar',stack=T)
平铺条图  xyflip=T
echartR(data = dtiris, x = ~Species, y = ~Mean, series = ~Param, 
        type = 'bar', palette='stata1', xyflip=T,
        title = 'Species-specific Mean by Parameters',
        subtitle = '(source: iris)', legend_pos=3,
        xlab = 'Species', ylab = 'Mean')
简化版
echartR(data = dtiris, x = ~Param, y = ~Mean,  series = ~Species,type = 'bar', xyflip=T)
堆积条图stack=T, xyflip=T
echartR(data = dtiris, x = ~Param, y = ~Mean, 
        series = ~Species, stack=T, xyflip=T,
        type = 'bar', palette='calc(5)',
        title = 'Parameter Mean by Species',
        subtitle = '(source: iris)',
        xlab = 'Parameter', ylab = 'Mean', legend_pos=3)
简化版
echartR(data = dtiris, x = ~Param, y = ~Mean,  series = ~Species,type = 'bar', stack=T,xyflip=T)
饼图 type='pie'
#生成数据
dtcars <- mtcars
dtcars$car <- row.names(dtcars)
dtcars$transmission <- as.factor(dtcars$am)
levels(dtcars$transmission) <- c("Automatic","Manual")
dtcars$cylinder <- as.factor(dtcars$cyl)
dtcars$carburetor <-as.factor(dtcars$carb)
#绘制
echartR(dtcars, x = ~transmission,  y = ~car, type='pie', palette='darkunica', 
        title='Number of cars by transmission', subtitle = '(source: mtcars)')
简化版--x对应的y的值所占比例
echartR(dtcars, x = ~transmission,  y = ~car, type='pie')
环图type='ring'
echartR(dtcars, x = ~cylinder,  y = ~car, type='ring', palette='hc', 
        title='Number of Cylinders', subtitle = '(source: mtcars)')
简化版--x对应的y的值所占比例
echartR(dtcars, x = ~cylinder,  y = ~car, type='ring')
玫瑰图 type='rose'
echartR(dtcars, x = ~cylinder,  y = ~car, type='rose',
        palette='colorblind', title='Number of Cylinders',
        subtitle = '(source: mtcars)')
简化版--x对应的y的值所占比例

echartR(dtcars, x = ~cylinder,  y = ~car, type='rose')

R可视化绘图三-recharts_第4张图片

Line线图-折线图
平铺线图  type='line'
#生成数据
airquality$strDate <- with(airquality,paste(2015,Month,Day,sep="-"))
airquality$TempG <- cut(airquality$Temp,breaks=c(0,60,70,80,100))
airquality <- rbind(airquality,c(rep(NA,4),6,31),c(rep(NA,4),9,31))  #补6,9月份无31号的值
#绘制--每次显示一组31数据,每组数据按Z分组 动态显示每月的序列变化 Day每组都是1-31
echartR(airquality, x = ~Day, y= ~Wind, z=~Month, type='line', 
        symbolList='none', 
        palette='tableauBlRd', xlab = 'Days', ylab = 'Wind',
        title='Day-specific Wind by month (airquality)',
        pos=list(title=12,toolbox=3))
简化版
echartR(airquality, x = ~Day, y= ~Wind, z=~Month, type='line')

echartR(airquality, x = ~Day, y= ~Wind, type='line')

R可视化绘图三-recharts_第5张图片

线段平滑(type='linesmooth')
Echarts对缺失值默认不填补需要在数据前处理时自行作插值运算 初始显示30-70%(dataZoom=c(20,50))双坐标轴(yAxis1),将系列1、2(Ozone、Solar.R)显示于次y轴
airq <- melt(airquality[,c("Ozone","Solar.R","Wind","Temp","strDate")],
             id=c("strDate"))
#airQ <- melt(airquality[,c("Wind","Temp","Date")],
#             id=c("Date"))
echartR(airq, x = ~strDate, y= ~value, series= ~variable, type='linesmooth',
        symbolList='none', dataZoom=c(20,50),
        palette='tableauPrGy', ylab = 'Wind, Temp',xlab="Day",
        title='Climate measures by day', subtitle = '(source: airquality)',
        yAxis1=list(lab="Ozone, SolorR",series=c(1,2)))
echartR(airq, x = ~strDate, y= ~value, series= ~variable, type='linesmooth', 
        symbolList='none', dataZoom=c(20,50),
        palette='tableauPrGy', ylab = 'Wind, Temp',xlab="Day",
        title='Climate measures by day', subtitle = '(source: airquality)',yAxis1=list(lab="Ozone,SolorR"))
简化版--自己拖动下面的长度使X周显示出来

echartR(airq, x = ~strDate, y= ~value, series= ~variable, type='linesmooth', dataZoom=c(20,50))

R可视化绘图三-recharts_第6张图片

堆积线图 stack=T 关闭所有纵线(color='none'),并显示横向间条(banded=T)
echartR(dfiris, x = ~id, y= ~Value, series= ~Param, type='line',stack=T,
        palette='tableauBlRd12', xlab = 'Sample ID', ylab = 'Measure',
        yAxis=list(color='none',banded=T),
        title='Parameter measures', subtitle = '(source: iris)')
简化版
echartR(dfiris, x = ~id, y= ~Value, series= ~Param, type='line',stack=T)
堆积线段平滑,不显示标志图形
echartR(dfiris, x = ~id, y= ~Value, series= ~Param, type='linesmooth',stack=T,
        palette='tableauGnOr12', xlab = 'Sample ID', ylab = 'Measure',
        symbolList='none', yAxis=list(color='none'),
        title='Parameter measures', subtitle = '(source: iris)')
Area 面积图type='area' http://madlogos.github.io/recharts/files/echartR.html#intro- 搜索Tiled Area 平铺面积图
3.9 Area 面积图
3.10 Funnel 普通漏斗图
3.11 Radar 雷达图 就是极坐标系下的线图/面积图
Map 地图 type=c('map','china','point')
#chinapm25 <- enc2native(unlist(strsplit(paste0(readLines("China PM2.5.txt"), collapse=","),",")))
chinapm25 <-unlist(strsplit(paste0(readLines("China PM2.5.txt",encoding = "UTF-8"), collapse=","),","))
chinapm25 <- as.data.frame(matrix(chinapm25,byrow=T,ncol=4),stringsAsFactors=F)
names(chinapm25) <- c("City","PM25","ycoord","xcoord")
for (i in 2:4) chinapm25[,i] <- as.numeric(chinapm25[,i])
top5 <- head(chinapm25[order(chinapm25$PM25,decreasing=T),],5)
top5$Name <- "Top 5"
top5$effect <- T
top5 <- top5[,c(5,1,2,4,3,6)]
#Point 点标注
echartR(chinapm25, x=~City, y=~PM25, xcoord=~xcoord, ycoord=~ycoord,
        type=c('map','china','point'),title='PM2.5 in Chinese cities',
        subtitle="(source: PM25.in)",subtitle_url="http://pm25.in/",
        dataRange=c("High","Low"), pos=list(toolbox=3), 
        dataRangePalette=c('maroon','red','orange','yellow','lightgreen','green'),
        markPoint=top5)

Area 区块标注 type=c('map','china','area')
gdp <- readLines("ChinaGDP.txt",encoding = "UTF-8")
dtgdp <- unlist(strsplit(gdp,split=","))
dtgdp <- as.data.frame(t(matrix(dtgdp,nrow=3)),stringsAsFactors=F)
names(dtgdp) <- c('Year','Prov',"GDP")
dtgdp$GDP <- as.numeric(dtgdp$GDP) 
knitr::kable(dcast(dtgdp,Prov~Year,sum,value.var="GDP"), format='html',
         caption="Table: 2012-2014 GDP of Provinces in China (Million USD)")
top3 <- dcast(dtgdp[dtgdp$Prov %in% c("广东","江苏","山东"),c("Prov","GDP")],
              Prov~., sum)
top3 <- cbind(top3,rep("Top3",3),c(32.04,23.16,36.65),c(118.78,113.23,117.00),
              rep(T,3))
top3 <- top3[,c(3,1,2,4:6)]
names(top3) <- c("Series","Prov","GDP","Xcoord","Ycoord","Effect")
for (i in 1:2) top3[,i]<-as.character(top3[,i])


echartR(dtgdp, x = ~Prov, y = ~GDP, series= ~Year, 
        type=c('map','china','area'), palette='gdocs',
        title="GDPs of China Provinces, 2012-2014 (Million USD)",
        subtitle='(source: Wikipedia)',
        subtitle_url="https://raw.githubusercontent.com/madlogos/Shared_Doc/master/Shared_Documents/ChinaGDP.txt",
        dataRangePalette=c('red','orange','yellow','green','limegreen'),
        dataRange=c('High',"Low"),pos=list(toolbox=3),markPoint=top3)
Line 线标注
数据集要包括y(数量)、x(起点地名)、x1(终点地名)、series(数据系列)、xcoord(起点纬度)、ycoord(起点经度)、xcoord1(终点纬度)、ycoord1(终点经度)
flight <- readLines("CZflight.txt",encoding = "UTF-8")[1]
flight <- as.data.frame(matrix(unlist(strsplit(flight,",")),byrow=T,ncol=2),
                        stringsAsFactors=F)
names(flight) <- c("From","To")
flightCoord <- readLines("CZflight.txt",encoding = "UTF-8")[2]
flightCoord <- as.data.frame(matrix(unlist(strsplit(flightCoord,",")),byrow=T,ncol=3),
                             stringsAsFactors=F)
for (i in 2:3) flightCoord[,i] <- as.numeric(flightCoord[,i])
names(flightCoord) <- c("City","Ycoord","Xcoord")
flight <- merge(flight,flightCoord,by.x="From",by.y="City",all.x=T)
flight <- merge(flight,flightCoord,by.x="To",by.y="City",all.x=T)
Tier1 <- dcast(flight,From~.,length)
Tier1 <- merge(Tier1,unique(flight[,c("From","Xcoord.x","Ycoord.x")]),by="From",all.x=T)
Tier1$effect <- T
Tier1 <- Tier1[,c(1,1:5)]
flight$y <- 0
echartR(flight, x=~From, x1=~To, y=~y, series=~From, xcoord=~Xcoord.x, ycoord=~Ycoord.x,
        xcoord1=~Xcoord.y, ycoord1=~Ycoord.y, type=c('map','china','line'),
        pos=list(toolbox=3), title="南方航空公司主要航班线路",markPoint=Tier1)
R可视化绘图三-recharts_第7张图片
全国迁移图
migrate <- as.data.frame(matrix(unlist(strsplit(readLines("CZflight.txt",encoding = "UTF-8")[3],",")),
                                byrow=T,ncol=2),stringsAsFactors=F)
names(migrate) <- c("From","To")
migrateCoord <- as.data.frame(matrix(unlist(strsplit(readLines("CZflight.txt",encoding = "UTF-8")[4],",")),
                                byrow=T,ncol=3),stringsAsFactors=F)
for (i in 2:3) migrateCoord[,i] <- as.numeric(migrateCoord[,i])
names(migrateCoord) <- c("City","Ycoord","Xcoord")
migrate <- merge(migrate,migrateCoord,by.x="From",by.y="City",all.x=T)
migrate <- merge(migrate,migrateCoord,by.x="To",by.y="City",all.x=T)
migrate$series <- "全国"
# markLine source data
migrateEm <- as.data.frame(matrix(unlist(strsplit(readLines("CZflight.txt",encoding = "UTF-8")[5],",")),
                                byrow=T,ncol=3),stringsAsFactors=F)
migrateEm[,3] <- as.numeric(migrateEm[,3])
names(migrateEm) <- c("From","To","NFlights")
#migrate <- merge(migrate,migrateEm,by=c("From","To"),all.x=T)
#migrate$Val[is.na(migrate$Val)] <- "-"
migrate$NFlights <- 0
migrateEm <- merge(migrateEm, migrateCoord, by.x="From",by.y="City",all.x=T)
migrateEm <- merge(migrateEm, migrateCoord, by.x="To",by.y="City",all.x=T)
# markLine dataset (8 col)
markline <- migrateEm[,c(2,1,3,5,4,7,6)]
markline$To <- paste(markline$From,markline$To,sep="/")
markline$effect <- T
# markPoint dataset (6 col)
markpoint <- migrateEm[,c(2,1,3,7,6)]
markpoint$effect <- T
# plot
echartR(migrate, x=~From, x1=~To, y=~NFlights, series=~series, xcoord=~Xcoord.x,
          ycoord=~Ycoord.x, xcoord1=~Xcoord.y, ycoord1=~Ycoord.y,
        type=c('map','china','line'), palette=c("Gray","Orange","Green","Purple"),
        pos=list(toolbox=3), title="百度迁徙(模拟数据)", dataRange=c("High","Low"),
        dataRangePalette=c("red","orange",'gold','green1','aquamarine2','royalblue4'),
        legend=list(mode='single',select=c('北京')), 
        markLinesmooth=markline, markPoint=markpoint, 
        theme=list(backgroundColor="#1b1b1b", borderColor="royalblue4",

                   borderWidth=0.5))

R可视化绘图三-recharts_第8张图片

3.13 Wordcloud 词云
hotword=read.table("BaiduWord.txt",header = FALSE,sep="\t")
names(hotword) <- c("Keyword","Freq")
echartR(hotword[1:30,], x=~Keyword, y=~Freq, type="wordcloud", 
        title="Baidu Word Search Top 30", palette=NULL,
        title_url="http://top.baidu.com/buzz?b=1", 

        subtitle="Tuesday, Auguest 18, 2015")

R可视化绘图三-recharts_第9张图片

简化版
echartR(hotword[1:30,], x=~Keyword, y=~Freq, type="wordcloud")
3.14 Chord 和弦图 http://madlogos.github.io/recharts/files/echartR.html#map-
Force 力导向布局图
3.16 Candlestick K线图
3.17 Gauge 仪表盘

你可能感兴趣的:(R)