代码之家  ›  专栏  ›  技术社区  ›  Trexion Kameha

python plotly:dataframe中使用列的方框图

  •  2
  • Trexion Kameha  · 技术社区  · 7 年前

    我很喜欢使用plotly,想为我的数据绘制箱线图。

    在他们的网站上,我做了以下工作:

    import plotly.plotly as py
    import plotly.graph_objs as go
    
    import numpy as np
    
    y0 = np.random.randn(50)
    y1 = np.random.randn(50)+1
    
    trace0 = go.Box(
        y=y0,
        name = 'Sample A',
        marker = dict(
            color = 'rgb(214, 12, 140)',
        )
    )
    trace1 = go.Box(
        y=y1,
        name = 'Sample B',
        marker = dict(
            color = 'rgb(0, 128, 128)',
        )
    )
    data = [trace0, trace1]
    py.iplot(data)
    

    我面临的挑战是,我不知道“跟踪”的总数是未知的。例如:

    titanic = pd.read_csv("http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.csv")
    

    有人知道我怎么才能在plotly中正确地做到这一点吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Maximilian Peters    7 年前

    您可以在 embarked 并为每一个添加跟踪。在这种情况下,还有 nan

    for embarked in titanic.embarked.unique():
    

    enter image description here

    import plotly
    plotly.offline.init_notebook_mode()
    import pandas as pd
    import numpy as np
    
    titanic = pd.read_csv("http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.csv")
    
    traces = list()
    for embarked in titanic.embarked.unique():
        if str(embarked) == 'nan':
           traces.append(plotly.graph_objs.Box(y=titanic[pd.isnull(titanic.embarked)].fare,
                                                name = str(embarked)
                                                )
                         )
        else:
            traces.append(plotly.graph_objs.Box(y=titanic[titanic.embarked == embarked].fare,
                                                name = embarked
                                                )
                         )
    plotly.offline.iplot(traces)