分享

六一双倍的快乐,ggplot2绘制双y轴图

 生信探索 2023-06-01 发布于云南

双y轴图的目的,是想要在同一坐标系中画两组数据,但是他们值范围差很多,比如一组数据是1-10,另一组是10-100,那么可以对第一组数据做数据变化,比如第一组数据乘以 10,然后在对应的y轴上写上1-10,虽然第一组的数据已经变成了10-100。

这种数据变换叫做归一化(Normalization,又称Min-Max Scaling)

把数值型某一特征缩放到最大值和最小值在某个范围,在sklearn中使用MinMaxScaler可以归一化处理特征矩阵。

from sklearn.preprocessing import MinMaxScaler
a = np.arange(1,11).reshape(-1,1)
scaler = MinMaxScaler(feature_range=(10,100)) #实例化
scaler = scaler.fit(a) #fit,在这里本质是生成min(x)和max(x)
scaler.transform(a) #通过接口导出结果

数学计算过程

在R中可以使用scales::rescale函数把某一组数据变化到某一范围。

using(scales)
a=1:10
scales::rescale(a,c(10,100))

画图

想要模仿文献中的最右边的双坐标图(barplot+lineplot)

  • 演示数据
#             R        P
#  1: -0.5186650 3.363205
#  2: -0.5033615 3.168150
#  3:  0.4924422 3.034439
#  4: -0.4785956 2.871116
#  5: -0.4725588 2.802014
#  6: -0.4591719 2.653164
#  7:  0.4565071 2.624237
#  8:  0.4556375 2.614848
#  9: -0.4548278 2.606127
# 10: -0.4533324 2.590075
# 11: -0.4529072 2.585524
# 12:  0.4527432 2.583770
# 13: -0.4521214 2.577129
# 14: -0.4510678 2.565903
# 15: -0.4478618 2.531959
# 16:  0.4413370 2.463869
# 17: -0.4411496 2.461933
# 18: -0.4392941 2.442820
# 19:  0.4379135 2.428666
# 20: -0.4378894 2.428420

实例数据中R得范围是[-0.5186650,0.4924422],所以可以把坐标轴的范围设置为x_min_max=[-0.6,0.5]。

在ggplot2图形映射中(geom_line、geom_point),都把P列的范围放缩到x_min_max这个范围,但是在坐标轴上标出真实的值范围p_min_max。

细调,coord_flip反转x轴和y轴,在theme中修改axis.title的颜色

r_min_max <- range(plot_data$R)
p_min_max <- range(plot_data$P)
x_min_max <- c(-0.6,0.5)
r_color <- "tan"
r_colorp_color <- "skyblue"
ggplot(plot_data,aes(x = Pathway)) +
    geom_col(aes(y = R),fill=r_color,alpha=.5) +
    geom_line(aes(y = rescale(P,x_min_max), group=1),size=2,color=p_color) +
    geom_point(aes(y = rescale(P,x_min_max)),shape=21,fill="white",size=4)+
    lims(y=x_min_max)+
    scale_y_continuous(breaks=breaks_pretty(3),sec.axis = sec_axis( ~rescale(.,r_min_max),name = "Pearson R"))+
    scale_x_discrete(breaks = NULL)+
    coord_flip()+
    labs(y="-log10(P-value)")+
    theme_base(base_size=16) %+replace%
    theme(
    axis.title.x.bottom=element_text(color=r_color),
    axis.title.x.top=element_text(color=p_color),
    axis.title.y = element_blank(),
    panel.border = element_blank(),
    axis.line = element_blank(),
    plot.margin=unit(c(0.5,0.5,0.5,0.5), 'cm'),
    )

Reference

https:///line-chart-dual-Y-axis-ggplot2.html

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约