使用Python,matplotlib绘制Nomogram列线图
1. 效果图2. 源码参考这篇博客将介绍如何使用Python,matplotlib绘制列线图。写这篇博客源于博友的提问
期望使用matplotlib绘制列线图如下,翻官网文档,尝试后终于绘制出来了。
1. 效果图
2. 源码
# 绘制列线图import matplotlib.pyplot as pltfrom matplotlib import tickerimport matplotlib# 注意注释掉此句,才可以plt.show()看到效果图# 设置此才可保存图片到本地,plt.savefig将保存结果图,但同时plt.show()将不在起作用# matplotlib.use("Agg")# 设置展示的刻度# 设置刻度轴位置# 刻度起始值、结束值、刻度最小精度、刻度间隔# 文字位置def setup(ax, title, minx, maxx, major, minor, position="bottom"):# 只显示底部脊椎ax.yaxis.set_major_locator(ticker.NullLocator())ax.spines['right'].set_color('none')ax.spines['left'].set_color('none')if (position == "bottom"):ax.spines['top'].set_color('none')elif (position == "top"):ax.spines['bottom'].set_color('none')# 定义刻度最大最小精度ax.xaxis.set_major_locator(ticker.MultipleLocator(major))ax.xaxis.set_minor_locator(ticker.MultipleLocator(minor)) # 最小刻度精度# 定义刻度位置ax.xaxis.set_ticks_position(position)ax.set_xlim(minx, maxx)ax.text(-0.5, -0.3, title, transform=ax.transAxes,fontsize=9, fontname='Monospace', color='black')fig, axs = plt.subplots(9, 1, figsize=(8, 6))# fig.suptitle("Nomogram demo") # 设置标题setup(axs[0], title="Points", position="top", minx=0, maxx=100, major=10, minor=2.5)axs[0].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))setup(axs[1], title="Age", minx=35, maxx=85, major=5, minor=5)axs[1].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))setup(axs[2], title="Blood Glucose", minx=100, maxx=50, major=10, minor=10)axs[2].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))setup(axs[3], title="Gender", minx=1, maxx=0, major=1, minor=1)axs[3].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))setup(axs[4], title="TotalPoints", minx=0, maxx=260, major=20, minor=4)axs[4].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))setup(axs[5], title="Linear Predictor", minx=-0.8, maxx=0.8, major=0.2, minor=0.1)axs[5].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))setup(axs[6], title="1-yearSurvival Probability", minx=0.85, maxx=0.5, major=0.05, minor=0.05)axs[6].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))setup(axs[7], title="3-yearSurvival Probability", minx=0.5, maxx=0.05, major=0.05, minor=0.05)axs[7].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))setup(axs[8], title="5-yearSurvival Probability", minx=0.25, maxx=0.05, major=0.05, minor=0.05)axs[8].xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))fig.tight_layout()plt.show()# 保存图片# plt.savefig('nomogram.jpg')