Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

python - Plotly: Add line to bar chart

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()


First, the plot :

enter image description here

Now, the code

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'])

to:

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

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')

Complete snippet:

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...