首先,加载recharts
:
library(recharts)
线图Line plot包括4个基本类型:
关键是:
x
和数值型y
x
(和series
) 的各水平的每个组合只能对应一个y
数据点echartr(data, x, y, <series>, <weight>, <t>, <type>, <subtype>)
参数 | 要求 |
---|---|
data |
数据框格式的源数据 |
x |
文本型自变量,其他类型会被转为因子。如提供多个变量,只传入第一个。 |
y |
数值型应变量。如提供多个变量,只传入第一个。 |
series |
数据系列变量,转为因子后计算。如提供多个变量,只传入第一个。 |
weight |
权重变量映射各系列的线宽lineWidth。 |
t |
时间轴变量,转为因子后计算。如提供多个变量,只传入第一个。 |
type |
‘line’, ‘curve’, ‘area’, ‘wave’ |
subtype |
|
让我们使用datasets
包自带数据集airquality
。数据结构如下:
aq <- airquality
aq$Date <- as.Date(paste('1973', aq$Month, aq$Day, sep='-'))
aq$Day <- as.character(aq$Day)
aq$Month <- factor(aq$Month, labels=c("May", "Jun", "Jul", "Aug", "Sep"))
head(aq)
## Ozone Solar.R Wind Temp Month Day Date
## 1 41 190 7.4 67 May 1 1973-05-01
## 2 36 118 8.0 72 May 2 1973-05-02
## 3 12 149 12.6 74 May 3 1973-05-03
## 4 18 313 11.5 62 May 4 1973-05-04
## 5 NA NA 14.3 56 May 5 1973-05-05
## 6 28 NA 14.9 66 May 6 1973-05-06
type
设为’line’。
echartr(aq, Date, Temp, type='line') %>%
setTitle('NY Temperature May - Sep 1973') %>% setSymbols('none')
echartr(aq, Day, Temp, Month, type='line') %>%
setTitle('NY Temperature May - Sep 1973, by Month') %>%
setSymbols('emptycircle')
设type
为’line’,subtype
为’stack’。
echartr(aq, Day, Temp, Month, type='line', subtype='stack') %>%
setTitle('NY Temperature May - Sep 1973, by Month') %>%
setSymbols('emptycircle')
Weight
把线宽和各系列(Month)风速均值关联起来。
echartr(aq, Day, Temp, Month, weight=Wind, type='line') %>%
setTitle('NY Temperature May - Sep 1973, by Month') %>%
setSymbols('emptycircle')
echartr(aq, Day, Temp, t=Month, type='line') %>%
setTitle('NY Temperature May - Sep 1973, by Month') %>%
setSymbols('emptycircle')
设type
为’curve’。
echartr(aq, Day, Temp, Month, type='curve') %>%
setTitle('NY Temperature May - Sep 1973, by Month') %>%
setSymbols('emptycircle')
设type
为’curve’,subtype
为’stack’。
echartr(aq, Day, Temp, Month, type='curve', subtype='stack') %>%
setTitle('NY Temperature May - Sep 1973, by Month') %>%
setSymbols('emptycircle')
面积图实际上和线图是一回事,唯一不同之处是前者设定了areaStyle
特性。
设type
为’area’。
echartr(aq, Date, Temp, type='area') %>%
setTitle('NY Temperature May - Sep 1973') %>%
setSymbols('emptycircle')
设type
为’area’,subtype
为’stack’。
echartr(aq, Day, Temp, Month, type='area', subtype='stack') %>%
setTitle('NY Temperature May - Sep 1973, by Month') %>%
setSymbols('emptycircle')
设type
为’wave’。
echartr(aq, Date, Temp, type='wave') %>%
setTitle('NY Temperature May - Sep 1973') %>%
setSymbols('emptycircle')
设type
为’wave’,subtype
为’stack’。
echartr(aq, Day, Temp, Month, type='wave', subtype='stack') %>%
setTitle('NY Temperature May - Sep 1973, by Month') %>%
setSymbols('emptycircle')
接下来可以配置控件、添加标注点/标注线,以及美化成图。
参考相关函数,尽情探索吧。