PAT*_*ARE 3 python pandas plotly
我有以下Python数据框,我想绘制Sno。使用plotly 与每列值进行比较。
\n TT AN AP AR AS BR CH CT DN DL ... PY PB RJ SK TN TG TR UP UT WB\nSno. \n1 81 0 1 0 0 0 0 0 0 7 ... 0 1 3 0 1 1 0 12 0 0\n2 27 0 0 0 0 0 0 0 0 0 ... 0 0 1 0 0 2 0 1 0 0\n3 15 0 0 0 0 0 0 0 0 0 ... 1 0 0 0 0 1 0 0 1 0\n4 11 0 0 0 0 0 0 0 0 1 ... 0 0 0 0 0 1 0 2 0 1\n5 37 0 0 0 0 0 0 0 0 2 ... 0 1 3 0 1 8 0 2 1 0\n... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...\n147 rows \xc3\x97 36 columns\nRun Code Online (Sandbox Code Playgroud)\n所以这是我的方法:
\ndef plot_case(df):\n for i in df.columns.values :\n dn = df.index.values\n dc = df[i].values\n xaxis = go.layout.XAxis(title="Day number")\n yaxis = go.layout.YAxis(title="New cases")\n\n fig = go.Figure(layout=go.Layout(title=i, xaxis=xaxis, yaxis=yaxis))\n fig.add_trace(go.Scatter(x=dn, y=dc))\nRun Code Online (Sandbox Code Playgroud)\nplot_case(df)\nRun Code Online (Sandbox Code Playgroud)\n但我在 jupyter 笔记本中没有得到任何输出,该单元只是运行而没有给出任何错误。
\n所以我对单列尝试了这种方法 TT尝试了这种方法
\nxaxis = go.layout.XAxis(title="Day number")\nyaxis = go.layout.YAxis(title="New cases")\n\nfig = go.Figure(layout=go.Layout(title="TT", xaxis=xaxis, yaxis=yaxis))\nfig.add_trace(go.Scatter(x=df.index.values, y=df.TT.values))\nRun Code Online (Sandbox Code Playgroud)\n它成功了!\n那么有人可以解释一下 for 循环出了什么问题吗?\n谢谢!
\n问题的根源在于 Jupyter Notebook 的行为以及它们如何确定单元输出。假设您有一个名为 的 pandas DataFrame df。如果您现在创建一个单元格并显示:
df
Run Code Online (Sandbox Code Playgroud)
执行时您将收到 DataFrame 作为该单元格的输出。但是,如果将单元格更改为
new_df = df
Run Code Online (Sandbox Code Playgroud)
或者
for i in range(5):
df
Run Code Online (Sandbox Code Playgroud)
您将不再收到任何输出。原因是,jupyter 笔记本默认总是输出最后收到的输出。的分配new_df = df不会返回任何内容。for 循环也不行。为了看到您的期望,您应该使用westland 的建议并将fig.show()or添加matplotplib.pyplot.plot()到您的 for 循环中。这样您就不会依赖 jupyter 笔记本的默认输出行为,但可以保证一些输出。
最后,你的代码变成:
def plot_case(df):
for i in df.columns.values :
dn = df.index.values
dc = df[i].values
xaxis = go.layout.XAxis(title="Day number")
yaxis = go.layout.YAxis(title="New cases")
fig = go.Figure(layout=go.Layout(title=i, xaxis=xaxis, yaxis=yaxis))
fig.add_trace(go.Scatter(x=dn, y=dc))
fig.show()
Run Code Online (Sandbox Code Playgroud)
如果你想要单独的地块,或者
def plot_case(df):
xaxis = go.layout.XAxis(title="Day number")
yaxis = go.layout.YAxis(title="New cases")
fig = go.Figure(layout=go.Layout(title='comparison', xaxis=xaxis, yaxis=yaxis))
dn = df.index.values
for i in df.columns.values :
dc = df[i].values
fig.add_trace(go.Scatter(x=dn, y=dc))
fig.show()
Run Code Online (Sandbox Code Playgroud)
如果您只想在一个图中进行比较。请注意,我将这些行从 for 循环中拉出,这些行不依赖于迭代值的效率。