正文
data2 <- data.frame(
Month = seq(from = as.Date('2017-01-01'),to=as.Date('2017-06-01'),by='1 month') %>% month(label=TRUE),
Categroy1 = runif(6,0.1,0.5) %>% round(2),
Categroy2 = runif(6,0.1,0.5) %>% round(2)
) %>% gather(Category,Value,-1)
Month Category Value
1 Jan Categroy1 0.49
2 Feb Categroy1 0.23
3 Mar Categroy1 0.10
4 Apr Categroy1 0.38
5 May Categroy1 0.34
6 Jun Categroy1 0.13
7 Jan Categroy2 0.48
8 Feb Categroy2 0.38
9 Mar Categroy2 0.48
10 Apr Categroy2 0.15
11 May Categroy2 0.40
12 Jun Categroy2 0.16
以下是整个过程代码,基本是司空见惯的内容,这里不做过多解释,仅提示其中两处重点,注意第二行geom_line内的y参数赋值以及第四行的scale_y_continuous语句:
ggplot() +
geom_col( data = data1,aes(x = Month,y = Value),fill="#6794a7") +
geom_line(data = data2,aes(x = Month,y = rescale(Value,c(0,55)),colour=Category,group=Category),size=1.5) +
geom_point(data = data2,aes(x = Month,y = rescale(Value,c(0,55)),colour=Category),shape=21,fill="white",size=4)+
scale_y_continuous(breaks=pretty_breaks(5),sec.axis = sec_axis( ~rescale(.,c(0,0.5)),name = "Categroy",labels=sprintf("%d%%",(0:5)*10)))+
scale_color_manual(label = c("Categroy1", "Categroy2"),values = c("#ee8f71","#C10534")) +
labs(
title="This is a Title!",
subtitle="This is a Subtitle",
caption="This is a Caption"
)+
theme_minimal(base_size=16) %+replace%
theme(
plot.caption = element_text(hjust=0),
plot.margin = unit(c(1,0.5,1,0.5), "lines")
)
这段代码与我们经常用的有两点不同: