之前就觉得Echart的可视化图表非常好看,最近碰巧看到了R语言接口,代码也非常简单易懂。比心:)
首先安装recharts包:(如果不行的话,请更新Rstudio版本至最新。)
if (!require(devtools)) library(devtools)
install_github("madlogos/recharts")
加载R包:
library(recharts)
参数和用法:
参数说明echartr(data,x,y,<series>,<weight>,<t>,<type>)
以iris数据集为例做图:
1. 单系列
花萼与花瓣宽度echartr(iris,x=Sepal.Width,y=Petal.Width)
2. 多系列(series标识系列)
不同种类的花萼与花瓣长度echartr(iris, x=Sepal.Width, y=Petal.Width, series = Species)
3. 气泡图
在散点图的基础上加入weight变量控制气泡大小,并且type设置为’bubble’
带权重的气泡图echartr(iris, Sepal.Width, Petal.Width, weight = Sepal.Length, type = 'bubble')
4. 颜色区分权重
splitNumber分割段数,为0时为线性渐变。
带权重的散点图echartr(iris, Sepal.Width, Petal.Width, weight = Petal.Length) %>%
setDataRange(calculable = TRUE, splitNumber = 0, labels = c('big','small'),
color = c('red','yellow','green'), valueRange = c(0,2.5))
5. 标注线addML和标注点addMP
标注点和标注线echartr(iris, Sepal.Width, Petal.Width, Species) %>%
addML(series = 1, data = data.frame(name1='Max', type='max')) %>%
addML(series = 2, data = data.frame(name1='Mean', type='average')) %>%
addML(series = 3, data = data.frame(name1='Min', type='min')) %>%
addMP(series = 2, data = data.frame(name1='Max', type='max'))
6. 增加拟合线
根据源数据线性回归,并定义拟合线的两个点。
拟合线lm <- with(iris, lm(Petal.Width~Sepal.Width))
pred <- predict(lm, data.frame(Sepal.Width=c(2.0,4.5)))
echartr(iris, Sepal.Width, Petal.Width, Species) %>%
addML(series = 'Linear Reg',data = data.frame(name1='Reg', value=lm$coefficients[2],
xAxis1 = 2,yAxis1 = pred[1],xAxis2 = 4.5,yAxis2 = pred[2]))
*7. 批量添加标注线
一次性添加标注线,映射到源数据的series。
lm <- with(iris, lm(Petal.Width~Sepal.Width))
pred <- predict(lm, data.frame(Sepal.Width=c(2.0,4.5)))
data <- data.frame(name1 = c('Max','Mean','Min'),type=c('max','average','min'),series = levels(iris$Species))
echartr(iris,Sepal.Width,Petal.Width,Species) %>%
addML(series=1:3,data=data) %>%
addMP(series=2,data=data.frame(name1='Max',type='max')) %>%
addML(series='Linear Reg', data=data.frame(name1 = 'Reg',value = lm$coefficients[2],
xAxis1 = 2,yAxis1 = pred[1],xAxis2 = 4.5,yAxis2=pred[2]))
更多功能请戳官方链接:madlogos.github.io/recharts/Basic_Plots_01_Scatterplot_cn.html#-en
网友评论