在同一个 IPython 笔记本单元格中制作多个图表

我已经开始我的 IPython 笔记本

ipython notebook --pylab inline

这是我的密码

df['korisnika'].plot()
df['osiguranika'].plot()

这是工作良好,它会画两条线,但在同一个图表。

我想在一个单独的图表上画每一条线。 如果图表能挨着放就好了,而不是一个接一个。

我知道我可以把第二行放在下一个单元格,然后我会得到两个图表。但我希望图表彼此靠近,因为它们代表相同的逻辑单位。

146666 次浏览

Make the multiple axes first and pass them to the Pandas plot function, like:

fig, axs = plt.subplots(1,2)


df['korisnika'].plot(ax=axs[0])
df['osiguranika'].plot(ax=axs[1])

It still gives you 1 figure, but with two different plots next to each other.

You can also call the show() function after each plot. e.g

   plt.plot(a)
plt.show()
plt.plot(b)
plt.show()

Another way, for variety. Although this is somewhat less flexible than the others. Unfortunately, the graphs appear one above the other, rather than side-by-side, which you did request in your original question. But it is very concise.

df.plot(subplots=True)

If the dataframe has more than the two series, and you only want to plot those two, you'll need to replace df with df[['korisnika','osiguranika']].

I don't know if this is new functionality, but this will plot on separate figures:

df.plot(y='korisnika')
df.plot(y='osiguranika')

while this will plot on the same figure: (just like the code in the op)

df.plot(y=['korisnika','osiguranika'])

I found this question because I was using the former method and wanted them to plot on the same figure, so your question was actually my answer.

Something like this:

import matplotlib.pyplot as plt
... code for plot 1 ...
plt.show()
... code for plot 2...
plt.show()

Note that this will also work if you are using the seaborn package for plotting:

import matplotlib.pyplot as plt
import seaborn as sns
sns.barplot(... code for plot 1 ...) # plot 1
plt.show()
sns.barplot(... code for plot 2 ...) # plot 2
plt.show()