简体   繁体   English

matplotlib和pandas在新行上绘制子图

[英]matplotlib and pandas plot subplots on a new row

I can plot my pandas dataframe column values as subplots easily in a 1XN matrix. 我可以在1XN矩阵中轻松绘制熊猫数据框列值作为子图。

However, when i want to plot it on a MXN matrix, i get errors. 但是,当我想将其绘制在MXN矩阵上时,会出现错误。

Example: 例:

df_play = pd.DataFrame({'a':['cat','dog','cat'],
                        'b':['apple','orange','orange'],
                        'c':['boy','boy','girl'],
                        'd':['chair','table','desk']
                       },dtype='category')


fig, axs = plt.subplots(1,len(df_play.columns),figsize=(14,6))
for i,x in enumerate(df_play.columns):
    df_play[x].value_counts().plot(kind='bar',ax=axs[i])

在此处输入图片说明

Doing this gives me errors( example i want to view my subplots as a 2X2 matrix): 这样做会给我带来错误(例如,我想将子图查看为2X2矩阵):

fig, axs = plt.subplots(2,len(df_play.columns)/2,figsize=(14,6))
for i,x in enumerate(df_play.columns):
    df_play[x].value_counts().plot(kind='bar',ax=axs[i])

AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'

When the subplots are 2-dimensional, subplots returns a figure and a 2-dimensional NumPy array of axes. 当子图为二维时, subplots返回图形和轴的二维NumPy数组。 Therefore, use 因此,使用

axs = axs.ravel()

to make the 2D array of axes 1-dimensional. 使轴的2D数组成为一维。 Then you can use axs[i] to index axs as desired: 然后,您可以根据需要使用axs[i]axs编制索引:

for i,x in enumerate(df_play.columns):
    df_play[x].value_counts().plot(kind='bar',ax=axs[i])

axs.ravel() enumerates the axes going from left to right across the rows from the top row down to the bottom row. axs.ravel()枚举从顶行到底行的各行从左到右的轴。 To enumerate the axes going from top to bottom down the columns from the left-most to the right-most column, use axs.ravel(order='F') . 要枚举从最左到最右的列从上到下的轴,请使用axs.ravel(order='F')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM