Skip to main content
 首页 » 编程设计

python plotly : box plot using column in dataframe

2024年10月01日10落叶无声

我很喜欢使用 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") 

我想绘制一个箱线图,按“登船”列,“票价”列的箱线图。由于“embarked”中唯一值的总数是未知的,我不想在其中进行硬编码。

有谁知道我怎样才能在 plotly 中正确地做到这一点?

谢谢!

请您参考如下方法:

您可以遍历 embarked 中的唯一值并为每个值添加一个跟踪。在这种情况下,还有 nan 需要单独处理。

for embarked in titanic.embarked.unique(): 

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)