如何使用 Pandas 数据框绘制条形图?

时间:2021-06-29 17:07:43

标签: pandas plotly

以下是数据透视图 df1 和 df2。现在我试图通过使用下面的数据框来绘制子图。但是我在执行我的代码时遇到关键错误。我的代码如下:

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
pio.renderers.default='browser'

df1 = Student   July    August
      Bobby     824     516

df2 = Country   July    August
       EUR      274     150 
       USA      212     128 
       China    113     170 
       Port     44      10


# plotly setup for fig
fig = make_subplots(2,1)
fig.add_trace(go.Bar(x=df1.Student, y=df1.loc['July','August']),row=1, col=1)

fig.add_trace(go.Bar(x=df2.Country, y=df2.loc['July','August']),row=2, col=1)
fig.show()

1 个答案:

答案 0 :(得分:1)

  • 您正在使用情节表达概念来创建轨迹。您需要为每个条形列创建跟踪
  • 然后将其添加到子图的简单案例
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np

s = 200
# generate pivot table dataframes similar to question
df = pd.DataFrame({"Student": np.random.choice(["Bob", "John", "Fred", "Jill", "Anne"], s),
              "Month": np.random.choice(
                  pd.Series(pd.date_range("31-Jan-2020", freq="M", periods=6)).dt.strftime("%B"),s),
              "score": np.random.randint(5, 75, s),
    })

df1 = df.groupby(["Student","Month"], as_index=False).agg({"score":"mean"}).pivot(index="Student", columns="Month", values="score")
df = pd.DataFrame({"Country": np.random.choice(["UK", "USA", "France", "Germany", "Mexico"], s),
              "Month": np.random.choice(
                  pd.Series(pd.date_range("31-Jan-2020", freq="M", periods=6)).dt.strftime("%B"),s),
              "score": np.random.randint(5, 75, s),
    })
df2 = df.groupby(["Country","Month"], as_index=False).agg({"score":"mean"}).pivot(index="Country", columns="Month", values="score")


# create figure
fig = make_subplots(rows=2, cols=1, specs=[[{"type":"bar"}],[{"type":"bar"}]])
# add traces
for col in ["April","May"]:
    fig.add_trace(go.Bar(x=df1.index, y=df1[col], name=col), row=1, col=1)
for col in ["April","May"]:
    fig.add_trace(go.Bar(x=df2.index, y=df2[col], name=col), row=2, col=1)

    
fig

enter image description here