Plotly:向条形图添加线条

fre*_*rtz 2 python plotly plotly-python

我有一个来自数据框的条形图:

fig = df.iplot(asFigure=True, kind='bar', barmode = 'relative')
py.iplot(fig)
Run Code Online (Sandbox Code Playgroud)

是否可以将数据框中的一列转换为线系列?

ves*_*and 6

评论中建议的链接确实有一些有价值的资源,但它们不会直接回答您的问题。iplot()使用 pandas 数据框作为输入,并生成堆叠条形图。这是一种方法,可以让您完全做到这一点,尽管不使用df.iplot()


首先,剧情:

在此输入图像描述

现在,代码

我的建议基于以下位置的示例:plot.ly/pandas/bar-charts。正如您将看到的,这是一个基于 pandas 数据框构建的示例 - 就像df.iplot(). 您可以简单地从堆叠条中取出一系列或“轨迹”,并通过更改将其显示为一条线

go.Bar(x=df['x'],
       y=df['y4'])
Run Code Online (Sandbox Code Playgroud)

到:

 go.Scatter(x=df['x'],
            y=df['y4'])
Run Code Online (Sandbox Code Playgroud)

我还添加了一些元素,以便更轻松地在 Jupyter 笔记本中离线显示结果。另请注意,我已将最后一行更改py.iplot(fig, filename='pandas-bar-chart-layout')iplot(fig, filename='pandas-bar-chart-layout')

完整片段:

import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot

init_notebook_mode(connected=True)

import pandas as pd
import numpy as np

N = 20
x = np.linspace(1, 10, N)
y = np.random.randn(N)+3
y2 = np.random.randn(N)+6
y3 = np.random.randn(N)+9
y4 = np.random.randn(N)+12
df = pd.DataFrame({'x': x, 'y': y, 'y2':y2, 'y3':y3, 'y4':y4})
df.head()

data = [
    go.Bar(
        x=df['x'], # assign x as the dataframe column 'x'
        y=df['y']
    ),
    go.Bar(
        x=df['x'],
        y=df['y2']
    ),
    go.Bar(
        x=df['x'],
        y=df['y3']
    ),
    go.Scatter(
        x=df['x'],
        y=df['y4']
    )

]

layout = go.Layout(
    barmode='stack',
    title='Stacked Bar with Pandas'
)

fig = go.Figure(data=data, layout=layout)

# IPython notebook
iplot(fig, filename='pandas-bar-chart-layout')
Run Code Online (Sandbox Code Playgroud)