我有一个来自数据框的绘图条形图:
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:将线添加到条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!