R语言使用ggplot绘制画中画细节放大的方法

这篇文章主要为大家介绍了R语言使用ggplot绘制画中画细节放大的方法实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步

当我们在利用ggplot绘图时,当遇到一些量纲相差过大,或者一些图的某些点排布密集时,需要将细节部分进行放大,这时我们就需要采用画中画的方式,或者将统计图的细节在旁边进行放大。

下面我们就来一步一步讲解如何将图中的细节进行放大(核心为ggforce包)。话不多说,先上最终效果图(以2019年双十一数据拟合为例):

1. 载入相关包

 library(ggplot2)  # 绘图核心 library(tidyr)    # 数据整理 library(ggforce)  # 画中画核心包 

2. 数据生成

我们收集了双十一销量数据,并进行一些处理,这里生成数据相对比较简单,就不进行解释了。

 # generate data year <- 2009:2019 sales <- c(0.5, 9.36, 52, 191, 350, 571, 912, 1207, 1682, 2135, 2684) growth_rate <- c(NA, diff(sales) / sales[1:(length(sales) - 1)] * 100) dat <- data.frame(year = factor(year), sales, growth_rate) # fit the curve of data dat_curve <- data.frame(year_std = 1:10, growth_rate = growth_rate[2:11] / 100) dat_curve$ind <- factor(c(rep(x = 1, 9), 2)) 

生成的数据长下面这样:

 year_std growth_rate ind 1         1  17.7200000   1 2         2   4.5555556   1 3         3   2.6730769   1 4         4   0.8324607   1 5         5   0.6314286   1 6         6   0.5971979   1 7         7   0.3234649   1 8         8   0.3935377   1 9         9   0.2693222   1 10       10   0.2571429   2 

3. 基础绘图

首先我们添加一些散点(geom_point),与拟合曲线(geom_smooth),并将2019年与历年区别开,代码如下:

 dat_curve %>% ggplot(aes(x = year_std, y = growth_rate, col = ind)) + geom_smooth(se = FALSE, method = "gam", formula = y ~ I(x^(-2)), size = 2, col = "#b3cde3") + geom_point(size = 4, alpha = 0.8) 

接着我们发现,在后面段这些散点在增长率上的差异看不出来了,因此需要使用画中画的方法,来对这部分进行放大。

4. 放大效果

其实非常简单facet_zoom(y = growth_rate <1),我们选取增长率小于1的部分进行放大即可:

 dat_curve %>% ggplot(aes(x = year_std, y = growth_rate, col = ind)) + geom_smooth(se = FALSE, method = "gam", formula = y ~ I(x^(-2)), size = 2, col = "#b3cde3") + geom_point(size = 4, alpha = 0.8) + facet_zoom(y = growth_rate <1) 

5. 绘图美化

最后,我们再添加一些代码进行美化即可!(美化的代码可以在我其他的博客中找到具体的解释哦)

 dat_curve %>% ggplot(aes(x = year_std, y = growth_rate, col = ind)) + geom_smooth(se = FALSE, method = "gam", formula = y ~ I(x^(-2)), size = 2, col = "#b3cde3") + geom_point(size = 4, alpha = 0.8) + labs(title = expression(paste('年份与销售额增长率拟合 (', R^2, " = 0.9978)")), x = "年份", y = "销售额增长率") + # 混合公式与中文,可参考本人另外的博客,相关的说明。 xlim(0, 10) + scale_y_continuous(labels = scales::percent) +   # y轴刻度改为百分数 scale_x_continuous(breaks = 1:10, labels = 2010:2019) + scale_fill_manual(values = c('#fbb4ae', '#ccebc5')) + theme_bw(base_family = "Times") + theme(axis.text.x = element_text(angle = 30), # x轴刻度倾斜30度 panel.grid.minor = element_blank(), legend.position = "none", text = element_text(family = "STHeiti"), plot.title = element_text(hjust = 0.5)) + facet_zoom(y = growth_rate <1) 

其他方法

其他几种ggplot绘制画中画的方法:

It is possible to create inset graphs?

Plots within plots with ggplot2 and ggmap

之后有时间我会补充另外一些利用ggplot进行画中画绘图的方法(觉得目前的绘制方式最好看且很简单,因此先讲解本博文中的方法)。

以上就是R语言使用ggplot绘制画中画细节放大的方法的详细内容,更多关于ggplot绘制画中画细节放大的资料请关注0133技术站其它相关文章!

以上就是R语言使用ggplot绘制画中画细节放大的方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » R语言