【问题标题】:Plotly: show dendogram and heatmap side by side in HTML filePlotly:在 HTML 文件中并排显示树状图和热图
【发布时间】:2021-07-25 04:45:06
【问题描述】:

我想在 HTML 文件中并排显示树状图和热图。 目前,我可以一个接一个地展示它们。 我尝试使用subplot,但无法理解需要添加哪些跟踪。 下面是我用来生成 HTML 输出的代码:

import plotly.graph_objects as go
import plotly.figure_factory as ff
import plotly
import numpy as np
from scipy.spatial.distance import pdist, squareform
import scipy.cluster.hierarchy as sch

# get data
data = np.genfromtxt("http://files.figshare.com/2133304/ExpRawData_E_TABM_84_A_AFFY_44.tab",
                     names=True,usecols=tuple(range(1,30)),dtype=float, delimiter="\t")
data_array = data.view((np.float, len(data.dtype.names)))
data_array = data_array.transpose()
labels = data.dtype.names



fig1 = ff.create_dendrogram(data_array,
                           linkagefun = lambda x: sch.linkage(x, "average"), labels=labels, orientation='bottom')
fig1.update_layout(title = 'Hierarchical Clustering', xaxis_title='Samples', title_font_color="Blue",
                    width=900, height=800)

# Initialize figure by creating upper dendrogram
fig = ff.create_dendrogram(data_array, orientation='bottom', labels=labels)
for i in range(len(fig['data'])):
    fig['data'][i]['yaxis'] = 'y2'

# Create Side Dendrogram
dendro_side = ff.create_dendrogram(data_array, orientation='right')
for i in range(len(dendro_side['data'])):
    dendro_side['data'][i]['xaxis'] = 'x2'

# Add Side Dendrogram Data to Figure
for data in dendro_side['data']:
    fig.add_trace(data)

# Create Heatmap
dendro_leaves = dendro_side['layout']['yaxis']['ticktext']
dendro_leaves = list(map(int, dendro_leaves))
data_dist = pdist(data_array)
heat_data = squareform(data_dist)
heat_data = heat_data[dendro_leaves,:]
heat_data = heat_data[:,dendro_leaves]

heatmap = [
    go.Heatmap(
        x = dendro_leaves,
        y = dendro_leaves,
        z = heat_data,
        colorscale = 'Blues'
    )
]

heatmap[0]['x'] = fig['layout']['xaxis']['tickvals']
heatmap[0]['y'] = dendro_side['layout']['yaxis']['tickvals']

# Add Heatmap Data to Figure
for data in heatmap:
    fig.add_trace(data)

# Edit Layout
fig.update_layout({'width':800, 'height':800,
                         'showlegend':False, 'hovermode': 'closest',
                         })
# Edit xaxis
fig.update_layout(xaxis={'domain': [.15, 1],
                                  'mirror': False,
                                  'showgrid': False,
                                  'showline': False,
                                  'zeroline': False,
                                  'ticks':""})
# Edit xaxis2
fig.update_layout(xaxis2={'domain': [0, .15],
                                   'mirror': False,
                                   'showgrid': False,
                                   'showline': False,
                                   'zeroline': False,
                                   'showticklabels': False,
                                   'ticks':""})

# Edit yaxis
fig.update_layout(yaxis={'domain': [0, .85],
                                  'mirror': False,
                                  'showgrid': False,
                                  'showline': False,
                                  'zeroline': False,
                                  'showticklabels': False,
                                  'ticks': ""
                        })
# Edit yaxis2
fig.update_layout(yaxis2={'domain':[.825, .975],
                                   'mirror': False,
                                   'showgrid': False,
                                   'showline': False,
                                   'zeroline': False,
                                   'showticklabels': False,
                                   'ticks':""})

# Plot!
with open('p_graph.html', 'a') as f:
    f.write(fig1.to_html(full_html=True, include_plotlyjs='cdn'))
    f.write(fig.to_html(full_html=True, include_plotlyjs='cdn'))
    

我想在输出 html 文件中并排显示 fig 和 fig1。

【问题讨论】:

  • 您是否愿意接受 HTML 解决方案而不是 subplots 解决方案?

标签: python plotly subplot figure


【解决方案1】:

由于您已经有了一个可行的绘图解决方案,我认为最快和最灵活的方法是编辑 HTML,而不是创建新的子图。如果他们有兴趣,我会把它留给其他人来解决make_subplots 解决方案。

这里是相关的 HTML sn-ps。请注意,为了满足 Stack Overflow 的帖子长度限制,我必须编辑出大部分的绘图输出。如果您想要完整的、可复制粘贴的版本,请参阅 here。要查看输出在浏览器中呈现的样子,请参阅here。

您的 HTML 输出文件如下所示:

<html>
<head><meta charset="utf-8" /></head>
<body>
    <div>                        <script type="text/javascript">window.PlotlyConfig = {MathJaxConfig: 'local'};</script>
        <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> 
</body>
</html><html>
<head><meta charset="utf-8" /></head>
<body>
    <div>                        <script type="text/javascript">window.PlotlyConfig = {MathJaxConfig: 'local'};</script>
        <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>     
</body>
</html>

如果你

  1. 删除文件中间多余的&lt;html&gt;、&lt;body&gt;和&lt;head&gt;标签,
  2. 将两个包含绘图的&lt;div&gt;s 与另外一个&lt;div style="width: 100%;"&gt; ... &lt;/div&gt; 包装起来,最后
  3. 将style 属性添加到包含绘图的&lt;div&gt;s 以适当定位它们,

编辑后的 ​​HTML 看起来像这样(同样不能复制粘贴——见上文):

<html>
<head><meta charset="utf-8" /></head>
<body>
    <div style="width: 100%;">
        <div style="width: 50%; float: left">                        <script type="text/javascript">window.PlotlyConfig = {MathJaxConfig: 'local'};</script>
            <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>                <div id="fe871eb9-b516-4575-8ce0-6116d52c7229" class="plotly-graph-div" style="height:800px; width:900px;"></div>     
        <div style="margin-left: 50%">                        <script type="text/javascript">window.PlotlyConfig = {MathJaxConfig: 'local'};</script>
            <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>                <div id="a148bd6e-da2a-4260-b1a5-94f96e8de9f3" class="plotly-graph-div" style="height:800px; width:800px;"></div> 
    </div>
</body>
</html>

请注意,有多种方法可以使用style 属性在页面上定位图表——这只是一个简单的示例,将style="width: 50%; float: left" 用于左侧图表,style="margin-left: 50%" 用于右侧图表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 2021-02-28
    • 1970-01-01
    相关资源
    最近更新 更多