Невозможно выполнить команду подзаголовка для нескольких графиков в matplotlib pyplot

#matplotlib #subplot

#matplotlib #подзаголовок

Вопрос:

это мой фрейм данных (с именем census):

     Ethnicity   USA All CA All  USA Children    CA Children
0   Black       0.12    0.05            0.14    0.05
1   Hispanic    0.18    0.38            0.24    0.50
2   White       0.62    0.39            0.52    0.29
3   Other       0.08    0.18            0.10    0.16
  

я пытаюсь показать параллельные графики, но, похоже, не могу найти, где я ошибаюсь
, это мой код:

 error im facing:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-32-c9aa8709606a> in <module>
----> 1 fig, (ax1,ax2,ax3,ax4) = plt.subplots(nrows = 2, ncols = 2)
      2 plt.tight_layout()
      3 ax1 = census[['USA All','CA All','Ethnicity']]
      4 ax1.plot.barh()
      5 

ValueError: not enough values to unpack (expected 4, got 2)
fig, (ax1,ax2,ax3,ax4) = plt.subplots(nrows = 2, ncols = 2)
plt.tight_layout()
ax1 = census[['USA All','CA All','Ethnicity']]
ax1.plot.barh()

ax2 = census[['USA All','CA Children','Ethnicity']]
ax2.plot.barh()

ax3 = census[['USA Children','CA Children','Ethnicity']]
ax3.plot.barh()

ax4 = census[['USA All','USA Children','Ethnicity']]
ax4.plot.barh()

plt.tight_layout()
  

Ответ №1:

Если фактор ошибки рисует более одного подзаголовка, вам необходимо сопоставить его матричную структуру со спецификацией ax, связывающей каждый график с ax. Созданные вами графики основаны на моих оценках и могут быть не такими, как вы предполагали.

 import matplotlib.pyplot as plt

fig, [[ax1,ax2],[ax3,ax4]] = plt.subplots(nrows=2, ncols=2, figsize=(12,9))

df1 = census[['Ethnicity','USA All','CA All']]
df1.plot(kind='barh', x='Ethnicity', y=['USA All','CA All'],ax=ax1)

df2 = census[['Ethnicity','USA All','CA Children']]
ax2 = df2.plot(kind='barh', x='Ethnicity', y=['USA All','CA Children'], ax=ax2)

df3 = census[['Ethnicity','USA Children','CA Children']]
ax3 = df3.plot(kind='barh', x='Ethnicity', y=['USA Children','CA Children'], ax=ax3)

df4 = census[['Ethnicity','USA All','USA Children']]
ax4 = df4.plot(kind='barh', x='Ethnicity', y=['USA All','USA Children'], ax=ax4)

plt.tight_layout()
  

введите описание изображения здесь