为条形图中的迹线编写函数 [英] Write a function for traces in a bar chart

查看:73
本文介绍了为条形图中的迹线编写函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个数据透视表:

I created a pivot table:

df = data.pivot_table(index='col_A', columns='col_B', values='col_C', fill_value=0)

数据帧df是10 * 25数据帧.我想将单个图形中的所有列绘制为迹线.但是,为所有25条轨迹编写代码将非常繁琐.有没有办法我可以写一个像这样的函数:

The dataframe df is a 10*25 dataframe. I want to plot all the columns in a single graph as traces. However, it would be super tedious to write code for all 25 traces. Is there a way I can write a function like:

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

上面的代码给我一个语法错误的错误.

The above code is giving me an error of invalid syntax.

推荐答案

为您的更好理解,我创建了一个示例:

I am created example for your better understanding:

# 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循环获取data中的所有traces. 您可以在这里看到两个barmode参数之间的区别: 1)barmode="stack"; 2)barmode="group".

In code above just use function to create traces. And using for loop after it to get all the traces in data. What difference between two barmode parameter you can see here: 1) barmode="stack"; 2) barmode="group".

您可以创建更漂亮的图表(请查看条形图的官方文档) ,只需指定其他参数即可.

You can create a much more beautiful plots (check official docs for bar chart), just specify additional parameters.

这篇关于为条形图中的迹线编写函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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