R語言使用ggplot繪制畫中畫細節(jié)放大的方法
當我們在利用ggplot
繪圖時,當遇到一些量綱相差過大,或者一些圖的某些點排布密集時,需要將細節(jié)部分進行放大,這時我們就需要采用畫中畫的方式,或者將統(tǒng)計圖的細節(jié)在旁邊進行放大。
下面我們就來一步一步講解如何將圖中的細節(jié)進行放大(核心為ggforce
包)。話不多說,先上最終效果圖(以2019年雙十一數(shù)據(jù)擬合為例):
1. 載入相關包
library(ggplot2) # 繪圖核心 library(tidyr) # 數(shù)據(jù)整理 library(ggforce) # 畫中畫核心包
2. 數(shù)據(jù)生成
我們收集了雙十一銷量數(shù)據(jù),并進行一些處理,這里生成數(shù)據(jù)相對比較簡單,就不進行解釋了。
# 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))
生成的數(shù)據(jù)長下面這樣:
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年與歷年區(qū)別開,代碼如下:
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)
接著我們發(fā)現(xiàn),在后面段這些散點在增長率上的差異看不出來了,因此需要使用畫中畫的方法,來對這部分進行放大。
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軸刻度改為百分數(shù) 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繪制畫中畫細節(jié)放大的方法的詳細內(nèi)容,更多關于ggplot繪制畫中畫細節(jié)放大的資料請關注腳本之家其它相關文章!
相關文章
R語言數(shù)據(jù)可視化學習之圖形參數(shù)修改詳解
這篇文章主要給大家介紹了關于R語言數(shù)據(jù)可視化學習之圖形參數(shù)修改的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03