Write a function for traces in a bar chart

╄→гoц情女王★ 提交于 2019-12-08 09:50:41

问题


I created a pivot table:

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

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.


回答1:


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

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.



来源:https://stackoverflow.com/questions/52335717/write-a-function-for-traces-in-a-bar-chart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!