Question

I ran the following code to get two plots next to each other (it is a minimal working example that you can copy):

import pandas as pd
import numpy as np
from matplotlib.pylab import plt

comp1 = np.random.normal(0,1,size=200)
values = pd.Series(comp1)

plt.close("all")
f = plt.figure()
plt.show()

sp1 = f.add_subplot(2,2,1)
values.hist(bins=100, alpha=0.5, color="r", normed=True)

sp2 = f.add_subplot(2,2,2)
values.plot(kind="kde")

Unfortunately, I then get the following image: enter image description here

This is also an interesting layout, but I wanted the figures to be next to each other. What did I do wrong? How can I correct it?

For clarity, I could also use this:

import pandas as pd
import numpy as np
from matplotlib.pylab import plt

comp1 = np.random.normal(0,1,size=200)
values = pd.Series(comp1)

plt.close("all")
fig, axes = plt.subplots(2,2)
plt.show()
axes[0,0].hist(values, bins=100, alpha=0.5, color="r", normed=True) # Until here, it works. You get a half-finished correct image of what I was going for (though it is 2x2 here)
axes[0,1].plot(values, kind="kde") # This does not work

Unfortunately, in this approach axes[0,1] refers to the subplot that has a plot method but does not know kind="kde". Please take into consideration that the in the first version plot is executed on the pandas object, whereas in the second version plot is executed on the subplot, which does not work with the kind="kde" parameter.

Was it helpful?

Solution

use ax= argument to set which subplot object to plot:

import pandas as pd
import numpy as np
from matplotlib.pylab import plt

comp1 = np.random.normal(0,1,size=200)
values = pd.Series(comp1)

plt.close("all")
f = plt.figure()
sp1 = f.add_subplot(2,2,1)
values.hist(bins=100, alpha=0.5, color="r", normed=True, ax=sp1)

sp2 = f.add_subplot(2,2,2)
values.plot(kind="kde", ax=sp2)

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top