簡體   English   中英

繪圖圖上的輔助/平行X軸(python)

[英]Secondary / Parallel X-Axis on Plotly charts (python)

我需要在Kaplan Meier圖上繪制at_risk數字。

最終結果應與此類似:

在此處輸入圖片說明

我在渲染時遇到的困難是圖表底部No. of patients at risk中的No. of patients at risk人數。 在那里顯示的值對應於x軸上的值。 因此,從本質上講,它就像與X平行繪制的Y軸。

我一直在嘗試復制在這里找到的多軸( https://plot.ly/python/multiple-axes/ )並沒有成功,並且還嘗試了一個子圖並隱藏除X軸以外的所有內容,但隨后它的值可以了與上圖不符。

最好的方法是什么?

您可以通過使用子圖來繪制有Plotly風險患者的Kaplan-Meier生存圖。 第一個圖具有存活率,第二個圖是散點圖,其中僅顯示文本,即未顯示標記。

這兩個圖都有相同的y軸,並且將處於危險狀態的患者分別繪制在x值上。

更多示例在這里: https : //github.com/Ashafix/Kaplan-Meier_Plotly

實施例1-男性和女性患者中的肺癌

import pandas as pd
import lifelines
import plotly
import numpy as np
plotly.offline.init_notebook_mode()

df = pd.read_csv('http://www-eio.upc.edu/~pau/cms/rdata/csv/survival/lung.csv')

fig = plotly.tools.make_subplots(rows=2, cols=1, print_grid=False)
kmfs = []

dict_sex = {1: 'Male', 2: 'Female'}

steps = 5 # the number of time points where number of patients at risk which should be shown

x_min = 0 # min value in x-axis, used to make sure that both plots have the same range
x_max = 0 # max value in x-axis

for sex in df.sex.unique():
    T = df[df.sex == sex]["time"]
    E = df[df.sex == sex]["status"]
    kmf = lifelines.KaplanMeierFitter()

    kmf.fit(T, event_observed=E)
    kmfs.append(kmf)
    x_max = max(x_max, max(kmf.event_table.index))
    x_min = min(x_min, min(kmf.event_table.index))
    fig.append_trace(plotly.graph_objs.Scatter(x=kmf.survival_function_.index,
                                               y=kmf.survival_function_.values.flatten(),  
                                               name=dict_sex[sex]), 
                     1, 1)


for s, sex in enumerate(df.sex.unique()):
    x = []
    kmf = kmfs[s].event_table
    for i in range(0, int(x_max), int(x_max / (steps - 1))):
        x.append(kmf.iloc[np.abs(kmf.index - i).argsort()[0]].name)
    fig.append_trace(plotly.graph_objs.Scatter(x=x, 
                                               y=[dict_sex[sex]] * len(x), 
                                               text=[kmfs[s].event_table[kmfs[s].event_table.index == t].at_risk.values[0] for t in x], 
                                               mode='text', 
                                               showlegend=False), 
                     2, 1)

# just a dummy line used as a spacer/header
t = [''] * len(x)
t[1] = 'Patients at risk'
fig.append_trace(plotly.graph_objs.Scatter(x=x, 
                                           y=[''] * len(x), 
                                           text=t,
                                           mode='text', 
                                           showlegend=False), 
                 2, 1)


# prettier layout
x_axis_range = [x_min - x_max * 0.05, x_max * 1.05]
fig['layout']['xaxis2']['visible'] = False
fig['layout']['xaxis2']['range'] = x_axis_range
fig['layout']['xaxis']['range'] = x_axis_range
fig['layout']['yaxis']['domain'] = [0.4, 1]
fig['layout']['yaxis2']['domain'] = [0.0, 0.3]
fig['layout']['yaxis2']['showgrid'] = False
fig['layout']['yaxis']['showgrid'] = False

plotly.offline.iplot(fig)

在此處輸入圖片說明 實施例2-不同治療方法的結腸癌

df = pd.read_csv('http://www-eio.upc.edu/~pau/cms/rdata/csv/survival/colon.csv')

fig = plotly.tools.make_subplots(rows=2, cols=1, print_grid=False)
kmfs = []

steps = 5 # the number of time points where number of patients at risk which should be shown

x_min = 0 # min value in x-axis, used to make sure that both plots have the same range
x_max = 0 # max value in x-axis

for rx in df.rx.unique():
    T = df[df.rx == rx]["time"]
    E = df[df.rx == rx]["status"]
    kmf = lifelines.KaplanMeierFitter()

    kmf.fit(T, event_observed=E)
    kmfs.append(kmf)
    x_max = max(x_max, max(kmf.event_table.index))
    x_min = min(x_min, min(kmf.event_table.index))
    fig.append_trace(plotly.graph_objs.Scatter(x=kmf.survival_function_.index,
                                               y=kmf.survival_function_.values.flatten(),
                                               name=rx), 
                     1, 1)


fig_patients = []
for s, rx in enumerate(df.rx.unique()):
    kmf = kmfs[s].event_table
    x = []
    for i in range(0, int(x_max), int(x_max / (steps - 1))):
        x.append(kmf.iloc[np.abs(kmf.index - i).argsort()[0]].name)
    fig.append_trace(plotly.graph_objs.Scatter(x=x, 
                                               y=[rx] * len(x), 
                                               text=[kmfs[s].event_table[kmfs[s].event_table.index == t].at_risk.values[0] for t in x], 
                                               mode='text', 
                                               showlegend=False), 
                     2, 1)

# just a dummy line used as a spacer/header
t = [''] * len(x)
t[1] = 'Patients at risk'
fig.append_trace(plotly.graph_objs.Scatter(x=x, 
                                           y=[''] * len(x), 
                                           text=t,
                                           mode='text', 
                                           showlegend=False), 
                 2, 1)


# prettier layout
x_axis_range = [x_min - x_max * 0.05, x_max * 1.05]
fig['layout']['xaxis2']['visible'] = False
fig['layout']['xaxis2']['range'] = x_axis_range
fig['layout']['xaxis']['range'] = x_axis_range
fig['layout']['yaxis']['domain'] = [0.4, 1]
fig['layout']['yaxis2']['domain'] = [0.0, 0.3]
fig['layout']['yaxis2']['showgrid'] = False
fig['layout']['yaxis']['showgrid'] = False

plotly.offline.iplot(fig)

在此處輸入圖片說明

這也是內置在生命線中的:

from lifelines import KaplanMeierFitter

ix = waltons['group'] == 'control'

ax = plt.subplot(111)

kmf_control = KaplanMeierFitter()
ax = kmf_control.fit(waltons.loc[ix]['T'], waltons.loc[ix]['E'], label='control').plot(ax=ax)

kmf_exp = KaplanMeierFitter()
ax = kmf_exp.fit(waltons.loc[~ix]['T'], waltons.loc[~ix]['E'], label='exp').plot(ax=ax)


from lifelines.plotting import add_at_risk_counts
add_at_risk_counts(kmf_exp, kmf_control, ax=ax)

https://lifelines.readthedocs.io/en/latest/Examples.html#displaying-multiple-at-risk-counts-below-plots

但是,我不確定這是否可以很好地配合使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM