其他
柱形图看腻了?不如试试这个
柱形图可以说是科研工作中最常见也最简单的一种统计图,相信大家绘制起来也是得心应手。而堆叠柱形图,则可以把多个元素叠加在一起,比如物种分布柱形图,它能够清晰的展示各个样本中优势物种的丰度情况。但如果是在不同时间段取样的,想要展示某些物种随时间的变化情况,那么普通的堆叠柱状图的表现就没有那么出彩了,今天小编就给大家介绍一种比较新颖的交互式堆叠柱形图,streamgraph,流图。
#获取绘图数据
library(ggplot2movies)
library(dplyr)
library(tidyr)
data("movies")
sub_movies <- movies %>% select(year, Action, Animation, Comedy, Drama, Documentary, Romance, Short)
data_plot <- gather(sub_movies, genre, value, -year) %>% group_by(year, genre) %>% tally()
(向左滑动查看更多)
最后生成的data_plot前10行如下:
year | genre | n |
1893 | Action | 1 |
1893 | Animation | 1 |
1893 | Comedy | 1 |
1893 | Documentary | 1 |
1893 | Drama | 1 |
1893 | Romance | 1 |
1893 | Short | 1 |
1894 | Action | 9 |
1894 | Animation | 9 |
1894 | Comedy | 9 |
#使用ggplot绘制普通的堆叠柱状图
library(ggplot2)
ggplot(data = data_plot, aes(x = year, y = n, fill = genre))+geom_bar(stat = "identity", position = "stack")
#可以看到,普通的堆叠柱形图中只能显示最下方的类别即“Short”这一类别的数量变化情况,其余类别的变化都不是很明显
(向左滑动查看更多)
#使用ggplot绘制流图(无法实现交互式)
library(ggTimeSeries)
ggplot(data = data_plot, aes(x = year, y = n, fill = genre))+stat_steamgraph()
(向左滑动查看更多)
#使用streamgraph绘制流图
#安装并加载streamgraph包
devtools::install_github("hrbrmstr/streamgraph")
library(streamgraph)
#生成交互式流图
streamgraph(data = data_plot, key = "genre", value = "n", date = "year")
#取消交互式
streamgraph(data = data_plot, key = "genre", value = "n", date = "year", interactive = FALSE)
#sg_axis_x:更改X轴间隔和显示格式;sg_axis_y:更改Y轴标签个数和显示格式;sg_fill_brewer:更改配色方案;sg_legend:显示图例
streamgraph(data = data_plot, key = "genre", value = "n", date = "year") %>% sg_axis_x(tick_interval = 20) %>% sg_axis_y(tick_count = 10) %>% sg_fill_brewer(palette = "PuOr") %>% sg_legend(show = TRUE, label = "Grenre:")
(向左滑动查看更多)
#当设置offset="zero"时,表示参考轴为0,相当于普通的堆叠柱形图
streamgraph(data = data_plot, key = "genre", value = "n", date = "year", offset = "zero", interactive = FALSE) %>% sg_axis_x(tick_interval = 20) %>% sg_axis_y(tick_count = 10) %>% sg_fill_brewer(palette = "YlGnBu")
#可以直接通过R图形界面的Export选项将结果保存为html或PNG
#或者通过htmlwidgets保存为html格式
library(htmlwidgets)
p <- streamgraph(data = data_plot, key = "genre", value = "n", date = "year", offset = "zero", interactive = FALSE) %>% sg_axis_x(tick_interval = 20) %>% sg_axis_y(tick_count = 10) %>% sg_fill_brewer(palette = "YlGnBu")
saveWidget(widget = p, file = "output.html")
#如果想要保存为pdf格式,可以通过webshot函数进行保存(phantomjs安装比较耗时)
library(webshot)
webshot::install_phantomjs()
#注意html文件路径中不能包含中文字符
webshot(url = "output.html" , file = "output.pdf", delay = 0.2)
webshot(url = "output.html" , file = "output.png", delay = 0.2, vwidth = 50, vheight = 50)
(向左滑动查看更多)
文:小师
排版:市场部
推荐阅读: