日常瞎掰
虽然双y坐标轴的图在文章中不是很常见,但个人觉得还是挺有意思的。相关的两个数据可以画在一起,一张图展现两个方面,简洁有内涵。可能也会有人觉得这样的图看起来稍显麻烦,相比于单y轴的图,信息的传递效率不高。Anyway,萝卜青菜各有所爱嘛。
示例1
话不多说,先用单细胞的数据来个简单的图,一张图展示各个cluster中细胞的比例和数量:
library(ggplot2)
head(df)
cluster number ratio
1 0 696 0.258
2 1 491 0.182
3 2 467 0.173
4 3 349 0.129
5 4 339 0.126
6 5 159 0.059
scalse_size <- max(df$number)/max(df$ratio)
p <- ggplot(df, aes(x=cluster,y=ratio)) +
geom_bar(alpha=0.5,stat='identity',width=0.5) +
scale_y_continuous('cell ratio',sec.axi=sec_axis(~.*scalse_size,
name = "cell number",breaks=seq(0,650,50)),
breaks=seq(0,0.25,0.05)) +
theme_test() +
theme(text=element_text(size=15),
axis.title.y.left=element_text(margin=unit(c(1,5,1,1),'mm')),
axis.title.y.right=element_text(margin=unit(c(1,1,1,5),'mm')))
p
结果如下:
![](https://img.haomeiwen.com/i23667126/910ccd5bff8f87ea.png)
示例2
下面再来一个稍微复杂一点的图,可以展示两个类别。由于两个类别都涉及到颜色的映射,想给每个类别都映射独立的颜色,这里借助一下ggnewscale
包的功能。
library(ggnewscale)
df <- data.frame(x=1:10,y1=(1:10)^2,y2=(1:10)^3)
scalse_size <- max(df$y2)/max(df$y1)
p <- ggplot(df, aes(x=x,y=y1,color='type1')) +
geom_point() +
scale_color_manual(values=c(type1='blue')) +
labs(color='') +
new_scale_color()+
geom_bar(aes(x,y2/scalse_size,fill='type2'),alpha=0.5,stat='identity') +
scale_y_continuous(sec.axi=sec_axis(~.*scalse_size,name = "y2")) +
theme(legend.key=element_blank()) +
labs(fill='') +
theme_test() +
theme(legend.position = 'top')
p
结果如下:
![](https://img.haomeiwen.com/i23667126/95bb80be63477e44.png)
结束语
双y坐标轴的图绘制原理还是相当简单的,就是将次坐标轴的取值范围映射为主坐标轴的取值范围,然后再利用ggplot2
中scale_y_continuous
函数的sec.axi
参数,设置一下次坐标的数据即可。另外,ggnewscale
作为扩展包,可以用来解决美学映射冲突的问题,例如在一张图上使用多个独立且相同的颜色、形状等映射体系。
往期回顾
tidydr | 一行代码搞定小坐标系
rnanorm | 一行命令搞定RNA-seq标准化
rGREAT | 基因组区间功能富集
利用UCSC预测启动子序列可能结合的转录因子
Vision | scRNA细胞相似性 + 差异signature
网友评论