密谋:在折线图中添加折线

施华兹

我有一个从数据框绘制的条形图:

fig = df.iplot(asFigure=True, kind='bar', barmode = 'relative')
py.iplot(fig)

是否可以将数据框中的一列变成一个行系列?

背心

评论中的建议链接确实具有一些宝贵的资源,但是它们不会直接回答您的问题。iplot()使用熊猫数据框作为输入,并生成一个堆叠的条形图。这是一种方法,即使您不使用它,也可以使您做到这一点df.iplot()


首先,剧情:

在此处输入图片说明

现在,代码

我的建议基于以下示例:plot.ly/pandas/bar-charts如您所见,这是一个基于pandas数据框的示例-就像df.iplot()您可以简单地从堆积的条形图中取出一系列或“轨迹”,然后通过更改将其显示为一行

go.Bar(x=df['x'],
       y=df['y4'])

至:

 go.Scatter(x=df['x'],
            y=df['y4'])

我还添加了一些元素,以便更轻松地在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')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章