python plotly : box plot using column in dataframe

标签 python pandas plotly boxplot

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

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)

关于 python plotly : box plot using column in dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46080545/

相关文章:

Python 删除或替换 key

python - 如何用 Pandas 选择重复的行?

python - 为什么 pandas.apply() 在空元素上执行?

python - 如何一次性编码 Pandas 数据帧的一列?

python - 如何增加plotly.express直方图中的x刻度

plotly - 如何在绘图破折号中的日期范围选择器之前获取文本标签?

python - Plotly:如何从两个数据框列中绘制两条线并从其他两列中分配悬停信息?

python - 是否可以在 python 中使用 http.server 显示目录中的文件大小?

python - 从 setup.py 构建一个万向轮

python - 更改 pycharm 中终端的 virtualenv