Plotly:如何为标准偏差制作具有多条线和阴影区域的图形?

Plotly: How to make a figure with multiple lines and shaded area for standard deviations?(Plotly:如何为标准偏差制作具有多条线和阴影区域的图形?)
本文介绍了Plotly:如何为标准偏差制作具有多条线和阴影区域的图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Plotly 生成带有阴影标准差的线图?我正在尝试实现类似于 seaborn.tsplot 的东西.任何帮助表示赞赏.

解决方案

以下方法对于 pandas 数据框中的列数是完全灵活的,并使用

完整代码:

# 导入导入 plotly.graph_objs将 plotly.express 导入为 px将熊猫导入为 pd将 numpy 导入为 np# pandas 数据框中的样本数据np.random.seed(1)df=pd.DataFrame(dict(A=np.random.uniform(low=-1, high=2, size=25).tolist(),B=np.random.uniform(low=-4, high=3, size=25).tolist(),C=np.random.uniform(low=-1, high=3, size=25).tolist(),))df = df.cumsum()# 将颜色定义为列表颜色 = px.colors.qualitative.Plotly# 将 plotly 十六进制颜色转换为 rgba 以启用透明度调整def hex_rgba(十六进制,透明度):col_hex = hex.lstrip('#')col_rgb = list(int(col_hex[i:i+2], 16) for i in (0, 2, 4))col_rgb.extend([透明度])areacol = 元组(col_rgb)返回区域rgba = [hex_rgba(c, transparent=0.2) for c in colors]colCycle = ['rgba'+str(elem) for elem in rgba]# 如果线条多于颜色,请确保颜色循环运行def next_col(cols):而真:对于 cols 中的 cols:产率line_color=next_col(cols=colCycle)# 情节图fig = go.Figure()# 为每个系列和标准差添加线条和阴影区域对于 i, col in enumerate(df):new_col = next(line_color)x = 列表(df.index.values+1)y1 = df[col]y1_upper = [(y + np.std(df[col])) for y in df[col]]y1_lower = [(y - np.std(df[col])) for y in df[col]]y1_lower = y1_lower[::-1]# 标准差区域fig.add_traces(go.Scatter(x=x+x[::-1],y=y1_upper+y1_lower,填充='tozerox',填充颜​​色=new_col,线=dict(颜色='rgba(255,255,255,0)'),showlegend=假,名称=列))# 线迹fig.add_traces(go.Scatter(x=x,y=y1,线=dict(颜色=new_col,宽度=2.5),模式='线',名称=列))# 设置 x 轴fig.update_layout(xaxis=dict(range=[1,len(df)]))图.show()

How can I use Plotly to produce a line plot with a shaded standard deviation? I am trying to achieve something similar to seaborn.tsplot. Any help is appreciated.

解决方案

The following approach is fully flexible with regards to the number of columns in a pandas dataframe and uses the default color cycle of plotly. If the number of lines exceed the number of colors, the colors will be re-used from the start. As of now px.colors.qualitative.Plotly can be replaced with any hex color sequence that you can find using px.colors.qualitative:

Alphabet = ['#AA0DFE', '#3283FE', '#85660D', '#782AB6', '#565656', '#1...
Alphabet_r = ['#FA0087', '#FBE426', '#B00068', '#FC1CBF', '#C075A6', '...
[...]

Complete code:

# imports
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd
import numpy as np

# sample data in a pandas dataframe
np.random.seed(1)
df=pd.DataFrame(dict(A=np.random.uniform(low=-1, high=2, size=25).tolist(),
                    B=np.random.uniform(low=-4, high=3, size=25).tolist(),
                    C=np.random.uniform(low=-1, high=3, size=25).tolist(),
                    ))
df = df.cumsum()

# define colors as a list 
colors = px.colors.qualitative.Plotly

# convert plotly hex colors to rgba to enable transparency adjustments
def hex_rgba(hex, transparency):
    col_hex = hex.lstrip('#')
    col_rgb = list(int(col_hex[i:i+2], 16) for i in (0, 2, 4))
    col_rgb.extend([transparency])
    areacol = tuple(col_rgb)
    return areacol

rgba = [hex_rgba(c, transparency=0.2) for c in colors]
colCycle = ['rgba'+str(elem) for elem in rgba]

# Make sure the colors run in cycles if there are more lines than colors
def next_col(cols):
    while True:
        for col in cols:
            yield col
line_color=next_col(cols=colCycle)

# plotly  figure
fig = go.Figure()

# add line and shaded area for each series and standards deviation
for i, col in enumerate(df):
    new_col = next(line_color)
    x = list(df.index.values+1)
    y1 = df[col]
    y1_upper = [(y + np.std(df[col])) for y in df[col]]
    y1_lower = [(y - np.std(df[col])) for y in df[col]]
    y1_lower = y1_lower[::-1]

    # standard deviation area
    fig.add_traces(go.Scatter(x=x+x[::-1],
                                y=y1_upper+y1_lower,
                                fill='tozerox',
                                fillcolor=new_col,
                                line=dict(color='rgba(255,255,255,0)'),
                                showlegend=False,
                                name=col))

    # line trace
    fig.add_traces(go.Scatter(x=x,
                              y=y1,
                              line=dict(color=new_col, width=2.5),
                              mode='lines',
                              name=col)
                                )
# set x-axis
fig.update_layout(xaxis=dict(range=[1,len(df)]))

fig.show()

这篇关于Plotly:如何为标准偏差制作具有多条线和阴影区域的图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)