pkgs = c('tidyverse', 'forcats', 'gtools', 'ggplot2', 'ggpubr', 'cowplot',
'scales', 'ggsci', 'viridis', 'hrbrthemes', 'Cairo', 'common')
# install.packages('pkgs')
inst = lapply(pkgs, library, character.only = TRUE)
# Build dummy data
data <- data.frame(
date = as.Date("2019-01-01") + 0:99,
day = 1:100,
season = rep(c('spring', 'summer', 'autumn', 'winter'), times = 25),
temperature = runif(100)/10,
price = runif(100)*10
)
data %>%
slice(1:3)
## date day season temperature price
## 1 2019-01-01 1 spring 0.006128101 4.149554
## 2 2019-01-02 2 summer 0.089528352 3.729223
## 3 2019-01-03 3 autumn 0.039876862 4.795942
set.seed(111)
df.raw <- data %>%
slice_sample(n = 20)
p <- df.raw %>%
mutate(day = factor(day, levels = unique(mixedsort(day)))) %>%
mutate(season = factor(season, levels = c('spring', 'summer', 'autumn', 'winter'))) %>%
ggplot(aes(x = day)) +
geom_bar(aes(y = temperature, fill = season), stat="identity")
p
# 默认条形图分面
p + facet_grid(.~season)
# 条形图分面宽度相同,只展示使用的因子水平
p + facet_grid(.~season, scale="free")
# 条形图分面宽度自动调整
p1 <- p + facet_grid(.~season, scale="free", space="free_x")
p1
p2 <- p1 + geom_line(aes(y=price / 100, group = 1), size = 1, linetype = 'dashed')
p2
p3 <- p2 + scale_y_continuous(
name = "First Axis",
sec.axis = sec_axis(~. * 100, name='Second Axis'))
p3
p4 <- p3 + theme_classic2(base_size = 16) +
scale_fill_simpsons() + theme(legend.position = 'top')
p4
# 例如给秋天autumn加上标数字1,用函数supsc()
p <- df.raw %>%
mutate(day = factor(day, levels = unique(mixedsort(day)))) %>%
mutate(season = factor(season, levels = c('spring', 'summer', 'autumn', 'winter'))) %>%
mutate(season = recode(season, "autumn" = paste0("autumn", supsc('1')) ) ) %>%
ggplot(aes(x = day)) +
geom_bar(aes(y = temperature, fill = season), stat="identity")
p + facet_grid(.~season, scale="free", space="free_x") +
geom_line(aes(y=price / 100, group = 1), size = 1, linetype = 'dashed') +
scale_y_continuous(name = "First Axis", sec.axis = sec_axis(~. * 100, name='Second Axis')) +
theme_classic2(base_size = 16) + scale_fill_simpsons() + theme(legend.position = 'top')
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有