iPython/Jupyter Notebook 和 Pandas,如何在 for 循环中绘制多个图形?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29532894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iPython/Jupyter Notebook and Pandas, how to plot multiple graphs in a for loop?
提问by alec_djinn
Consider the following code running in iPython/Jupyter Notebook:
考虑以下在 iPython/Jupyter Notebook 中运行的代码:
from pandas import *
%matplotlib inline
ys = [[0,1,2,3,4],[4,3,2,1,0]]
x_ax = [0,1,2,3,4]
for y_ax in ys:
ts = Series(y_ax,index=x_ax)
ts.plot(kind='bar', figsize=(15,5))
I would expect to have 2 separate plots as output, instead, I get the two series merged in one single plot.
Why is that? How can I get two separate plots keeping the for
loop?
我希望有 2 个单独的图作为输出,相反,我将两个系列合并为一个图。这是为什么?我怎样才能得到两个独立的图保持for
循环?
采纳答案by Andrey Sobolev
Just add the call to plt.show()
after you plot the graph (you might want to import matplotlib.pyplot
to do that), like this:
只需plt.show()
在绘制图形后添加调用(您可能想import matplotlib.pyplot
要这样做),如下所示:
from pandas import *
import matplotlib.pyplot as plt
%matplotlib inline
ys = [[0,1,2,3,4],[4,3,2,1,0]]
x_ax = [0,1,2,3,4]
for y_ax in ys:
ts = Series(y_ax,index=x_ax)
ts.plot(kind='bar', figsize=(15,5))
plt.show()
回答by jmz
In the IPython notebook the best way to do this is often with subplots. You create multiple axes on the same figure and then render the figure in the notebook. For example:
在 IPython notebook 中,最好的方法通常是使用子图。您在同一个图窗上创建多个轴,然后在笔记本中渲染图窗。例如:
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
ys = [[0,1,2,3,4],[4,3,2,1,0]]
x_ax = [0,1,2,3,4]
fig, axs = plt.subplots(ncols=2, figsize=(10, 4))
for i, y_ax in enumerate(ys):
pd.Series(y_ax, index=x_ax).plot(kind='bar', ax=axs[i])
axs[i].set_title('Plot number {}'.format(i+1))
generates the following charts
生成以下图表