簡體   English   中英

如何根據繪圖中的顏色制作具有可變寬度的矩形圖?

[英]How to make the rectangle plot with variable width based on color in plotly?

我是 plotly 的新手,我必須繪制一個矩形圖。 我的數據如下所示:

df:
start  end color
1       5   blue
6       50  grey
51      56  red
57      60  blue
61      105 grey
106     111 red

對於每一行,我需要創建一個矩形圖,其中包含從每行的開始列到結束列的顏色塊。 但是當顏色列中的值為灰色時,我想使繪圖具有固定值5,並希望在灰色結​​束后繼續下一個顏色。 在灰色之后,我無法從灰色結束后的下一個數字繼續繪圖。 簡而言之,我想讓矩形圖連續。

這是我當前的代碼:

import plotly.graph_objects as go
fig = go.Figure()
start = min(df['start'])
end = max(df['end'])

fig.update_xaxes(range=[start-100, end+100], showgrid=False)
fig.update_yaxes(range=[0, 2])
for row in df.index:
    color_rect = df['color'][row]
    if color_rect == 'grey':
        x_start = df['start'][row]
        x_stop = df['start'][row]+50
        fig.add_shape(type="rect",x0=x_start, y0=0.5, x1=x_stop, y1=1.5,
                line=dict(color=color_rect,),fillcolor=color_rect,)
        x_cont=x_stop+1
    else:
        x_start = df['start'][row]
        x_stop = df['end'][row]
        fig.add_shape(type="rect",x0=x_start, y0=0.5, x1=x_start, y1=1.5,
            line=dict(color=color_rect,),fillcolor=color_rect,)
fig.update_shapes(dict(xref='x', yref='y'))
fig.show()

這就是我當前的情節: 在此處輸入圖像描述

我想避免灰色后的空白。 請幫助解決這個問題!

代碼中幾乎沒有錯誤。

  • 你說如果顏色是灰色的寬度應該是5,但是你的代碼有50而不是5
  • x_cont 最初需要設置為 0,然后用作矩形的起點。 如果是灰色,寬度應為 5,否則為 df.end - df.start
  • 對於非灰色,x0 和 x1 都被稱為 x_start
  • 在這兩種情況下(無論是否為灰色),您都需要增加 x_cont

更新的代碼和情節如下。 數據與您的問題一樣。 希望這是您正在尋找的...

import plotly.graph_objects as go
fig = go.Figure()
start = min(df['start'])
end = max(df['end'])
x_cont = 0  ## Initialize x_cont to zero
fig.update_xaxes(range=[start-100, end+100], showgrid=False)
fig.update_yaxes(range=[0, 2])
for row in df.index:
    color_rect = df['color'][row]
    if color_rect == 'grey':
        x_start = x_cont ## Using x_cont instead of df.start
        x_stop = x_cont+5
        fig.add_shape(type="rect",x0=x_start, y0=0.5, x1=x_stop, y1=1.5,
                line=dict(color=color_rect,),fillcolor=color_rect,)
    else:
        x_start = x_cont ## Using x_cont instead of df.start
        x_stop = x_cont + df['end'][row] - df['start'][row] ## x_end is x_cont+width
        fig.add_shape(type="rect",x0=x_start, y0=0.5, x1=x_stop, y1=1.5,
            line=dict(color=color_rect,),fillcolor=color_rect,)
    x_cont=x_stop+1  ## Note that x_cont is updated in each loop of for loop
        
fig.update_shapes(dict(xref='x', yref='y'))
fig.show()

陰謀在此處輸入圖像描述

暫無
暫無

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

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