1

I am trying to make side by side bar graphs with overlays. The following code only produces the second plot, and makes two separate windows of blank plots - one on the left side and one on the right. Any help is appreciated!

import matplotlib.pyplot as plt

## Test data set
plt.subplot(1, 2, 1)
health_sex1.plot(kind = 'bar', stacked = True)
plt.title("Health with Sex Overlay")
plt.xlabel("Health")
plt.ylabel("Count")

plt.subplot(1, 2, 2)
health_educ1.plot(kind = 'bar', stacked = True)
plt.title("Health with Education Overlay")
plt.xlabel("Health")
plt.ylabel("Count")
plt.show

1 Answers1

1

Use plt.subplots() to create a subplot grid of ax1 and ax2. Then specify ax=ax1 and ax=ax2 to plot onto those premade axes:

fig, (ax1, ax2) = plt.subplots(1, 2)

health_sex1.plot.bar(ax=ax1, stacked=True)
ax1.set_title("Health with Sex Overlay")
ax1.set_xlabel("Health")
ax1.set_ylabel("Count")

health_educ1.plot.bar(ax=ax2, stacked=True)
ax2.set_title("Health with Education Overlay")
ax2.set_xlabel("Health")
ax2.set_ylabel("Count")
tdy
  • 36,675
  • 19
  • 86
  • 83