基于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()
并成功获得下面的图
但是,如果存在数据间隙,则填充的部分似乎无法正常工作(例如,第一和第二连接的组件),至少使用下面尝试的代码。
成功拥有数据空白和填充线的正确方法/代码是什么?
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()
最佳答案
这似乎是一个古老的密谋错误:
参考:
https://github.com/plotly/plotly.js/issues/1132
和:
https://community.plot.ly/t/scatter-line-plot-fill-option-fills-gaps/21264
一种解决方案可能是将整个填充痕迹分解为多个部分,并将其添加到图形中。但是,这可能有点复杂,因为需要不同的计算来确定该填充区域的位置。
通过将connectgaps属性设置为true,实际上可以稍微改善图表,结果是:
但是,这看起来有点奇怪;)