python - 当存在数据间隙时,如何在 Plotly 中创建正确填充的线

标签 python plotly data-visualization plotly-python

基于https://plot.ly/python/line-charts/#filled-lines ,可以运行下面的代码

import plotly.graph_objects as go

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x_rev = x[::-1]
y = [5, 2.5, 5, 7.5, 5, 2.5, 7.5, 4.5, 5.5, 5]
y_upper = [5.5, 3, 5.5, 8, 6, 3, 8, 5, 6, 5.5]
y_lower = [4.5, 2, 4.4, 7, 4, 2, 7, 4, 5, 4.75]
y_lower_rev = y_lower[::-1]

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=x, y=y,
    line_color='rgb(0,176,246)',
    name='Mid line',
))
fig.add_trace(go.Scatter(
    x=x+x_rev,
    y=y_upper+y_lower_rev,
    fill='toself',
    fillcolor='rgba(0,176,246,0.2)',
    line_color='rgba(255,255,255,0)',
    name='Filled lines working properly',
))
fig.update_traces(mode='lines')
fig.show()

并成功得到下图 enter image description here

但是,如果存在数据间隙,填充部分似乎无法正常工作(例如,第一个和第二个连接的组件),至少对于下面尝试的代码是这样。

成功实现数据间隙和填充行的正确方法/代码是什么?

x_for_gaps_example = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
x_for_gaps_example_rev = x_for_gaps_example[::-1]
y_with_gaps =[5, 15, None, 10, 5, 0, 10, None, 15, 5, 5, 10, 20, 15, 5]
y_upper_with_gaps = [i+1 if i is not None else None for i in y_with_gaps]
y_lower_with_gaps = [i-2 if i is not None else None for i in y_with_gaps][::-1]
fig = go.Figure()
fig.add_trace(go.Scatter(
    x=x_for_gaps_example,
    y=y_with_gaps,
    name='Mid Line with <b>Gaps</b>'
))

fig.add_trace(go.Scatter(
    x=x_for_gaps_example+x_for_gaps_example_rev,
    y=y_upper_with_gaps+y_lower_with_gaps,
    fill='toself',
    fillcolor='rgba(0,176,246,0.2)',
    line_color='rgba(255,255,255,0)',
    name='Filled Lines not working properly with <b>gaps</b>'
))

fig.show()

enter image description here

最佳答案

这似乎是一个相当古老的 plotly 错误:

引用:

https://github.com/plotly/plotly.js/issues/1132

和:

https://community.plot.ly/t/scatter-line-plot-fill-option-fills-gaps/21264

一种解决方案可能是将整个填充轨迹分解为多个部分并将它们添加到图中。然而,这可能有点复杂,因为它需要不同的计算来确定填充区域的位置。

实际上,您可以通过将 connectgaps 属性设置为 true 来稍微改进图表,结果如下:

enter image description here

但是,这看起来有点奇怪;)

关于python - 当存在数据间隙时,如何在 Plotly 中创建正确填充的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59490141/

相关文章:

python - 绘制悬停数据和悬停文本

python - "min() arg is an empty sequence"尝试将我的 Pandas plotly 转换为 plotly 时

用于可视化动态和分层图的 Java 图形库

python - PyMySQL 将(文件)数据加载到远程 MySQL 实例时出现错误/异常

python - 查找具有列表形式值的两个数据框之间的差异

python - 在 Python 上使用多进程包时,值未附加到列表中

python - 如何在一个模型中指定父子关系?

javascript - 在不重绘背景图的情况下以交互方式向 plotly R 中的子图添加点

python - Altair choropleth map ,基于折线图选择的颜色突出显示

c# - 我可以在 MSChart 的饼图标签上同时显示标签和值吗