Plotly:向条形图添加折线 [英] Plotly: Add line to bar chart

查看:106
本文介绍了Plotly:向条形图添加折线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a plotly bar chart, from a dataframe:

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

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

Is it possible to turn one of the columns in the data frame into a line series?

推荐答案

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

The suggested link in the comments does have some valuable resources, but they won't answer your questions directly. iplot() uses a pandas dataframe as input, and produces a stacked barplot. Here's an approach that will let you do exactly that, albeit without using df.iplot()

一、剧情:

现在,代码

我的建议基于以下示例:plot.ly/pandas/bar-charts.正如您将看到的,这是一个基于 Pandas 数据框的示例 - 就像 df.iplot().您可以简单地从堆叠的条形中取出一个系列或跟踪",并通过更改

My suggestion builds on an example found at: plot.ly/pandas/bar-charts. As you'll see that's an example that builds on a pandas dataframe - just like df.iplot(). You can simply take a series or 'trace' out of the stacked bars and display it as a line by changing

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-条形图布局')

I've also added a few elements to make it easier to display your results offline in a Jupyter notebook. Also note that I've changed the last line from py.iplot(fig, filename='pandas-bar-chart-layout') to just 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')

这篇关于Plotly:向条形图添加折线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆