我创建了一个数据透视表:
df = data.pivot_table(index='col_A', columns='col_B', values='col_C', fill_value=0)
数据帧df是10 * 25数据帧。我想将单个图形中的所有列绘制为迹线。但是,为所有25条跟踪编写代码会非常繁琐。有没有办法可以编写如下函数:
import plotly.plotly as py
import plotly.tools as tls
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
init_notebook_mode(connected=True)
iplot([go.Bars(x=df.index, y=df[col], name=col for col in df.columns)])
上面的代码给出了语法无效的错误。
我为您提供了更好理解的示例:
# import what we need
import plotly
import plotly.graph_objs as go
import pandas as pd
# Create DataFrame
df = pd.DataFrame({"A":[1,1,1,0],
"B":[1,1,0,0],
"C":[1,0,0,0]
})
# Convert names of columns in a list
traceslist = df.columns.tolist()
# Check list
print(traceslist)
# Create a function that will create as many traces for us as we need
def tracing(column):
trace = go.Bar(
x = df.index,
y = df[column],
# Parameters above specify what you would see if hover on any column
name = column,
text=column,
textposition='auto',
hoverinfo="x+y")
return trace
# Create data
data = []
# Fill out data with our traces
for i in range(len(traceslist)):
eachtrace = tracing(traceslist[i])
data.append(eachtrace)
# Optional: create layout
layout = go.Layout(
# Set title to plot
title = "Bam!",
# Choose one of the barmode below and comment another
barmode="stack",
#barmode="group"
)
# Create figure with all we need to plot
fig = go.Figure(data=data, layout=layout)
# Use offline plot without connection to plotly site
plotly.offline.plot(fig, filename='Bam.html')
在上面的代码中,只需使用函数来创建traces
。然后使用for
循环来获取traces
中的所有data
。你可以在这里看到两个barmode
参数有什么区别: 1)barmode="stack"
; 2)barmode="group"
。
你可以创建一个更漂亮的图(查看bar chart的官方文档),只需指定其他参数。