我们在处理数据的过程中,仅用一个轴标签往往无法准确表达一个数据集的实际含义,这种情况在较长的时间序列数据中十分常见。因此,我们需要添加多层分类标签,来显示数据的趋势或季节性变化。这里介绍一种简单的利用Excel显示多层分类轴标签的方法:百度经验
那么,如何在ggplot中实现呢?
library(tidyverse)
library(lubridate)
library(scales)
set.seed(123)
df <- tibble(
date = as.Date(41000:42000, origin = "1899-12-30"),
value = c(rnorm(500, 5), rnorm(501, 10))
)
# create year column for facet
df <- df %>%
mutate(year = as.factor(year(date)))
p <- ggplot(df, aes(date, value)) +
geom_line() +
geom_vline(xintercept = as.numeric(df$date[yday(df$date) == 1]), color = "grey60") +
scale_x_date(date_labels = "%b",
breaks = pretty_breaks(),
expand = c(0, 0)) +
# switch the facet strip label to the bottom
facet_grid(.~ year, space = 'free_x', scales = 'free_x', switch = 'x') +
labs(x = "") +
theme_classic(base_size = 14, base_family = 'mono') +
theme(panel.grid.minor.x = element_blank()) +
# remove facet spacing on x-direction
theme(panel.spacing.x = unit(0,"line")) +
# switch the facet strip label to outside
# remove background color
theme(strip.placement = 'outside',
strip.background.x = element_blank())
p
df<-read.csv("C:\\Users\\Administrator\\Desktop\\mm (2).csv",header = T,row.names = 1)# 人造数据,请勿模仿
head(df)
library(tidyverse)
df<-separate(data = df, col = variable, into = c("ZZ", "NT"), sep = "_")
head(df)
X ZZ NT value
1 x13 yFX02 N 0.3531287
2 x14 yFX02 N 0.5488629
3 x15 yFX02 N 1.6708033
4 x16 yFX02 N 1.1179046
5 x17 yFX02 N 4.1669189
6 x18 yFX02 N 3.9732026
ggplot(data = df, aes(x = interaction(ZZ, NT, lex.order = TRUE),
y = value,fill = X))+
geom_bar(stat = 'identity',position = 'stack')+
annotate(geom = "text", x = 1:(length(unique(df$ZZ))*2), y = -2, label = rep(c("N","G"),12), size = 3) +
annotate(geom = "text", x = 1.6 +2* (0:11), y = -6, label = unique(df$ZZ), size = 3) +
coord_cartesian(ylim = c(0, 100), expand = FALSE, clip = "off") +
theme_bw() +
theme(plot.margin = unit(c(1, 1, 4, 1), "lines"),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
legend.title=element_blank()
)