【问题标题】:Graph is drawn in extra figure, not in subplot图表是在额外的图中绘制的,而不是在子图中
【发布时间】:2021-11-09 17:33:51
【问题描述】:

我在python中练习了一些绘图方法,使用subplot时出现问题。

import matplotlib.pyplot as plt
import seaborn as sns

f, ax = plt.subplots(1, 2, figsize=(8, 8))
sns.barplot('A', 'B', data=data, ax=ax[0])
sns.factorplot('A', 'B', data=data, ax=ax[1])
plt.close(2)
plt.show()

我使用的代码在上面。我预计这会导致两个图表中的子图(左侧的条形图和右侧的因子图),但事实并非如此。 screenshot

因子图已经消失,我可以知道这个图在新生成的图中,并且由于plt.close(2) 而关闭。我想控制因子图的索引,但它似乎不起作用。有什么技巧可以解决这个问题吗?

【问题讨论】:

    标签: python matplotlib seaborn subplot


    【解决方案1】:

    seaborn.catplotseaborn.factorplot 的新 API)是用于分面网格的图形水平图,see here for details。因此ax 参数与catplot 一起不允许。将ax 传递给catplot 时,Seaborn 应打印以下警告:

    some_path_to_lib\seaborn\categorical.py:3762:用户警告:catplot 是图形级函数,不接受目标轴。你不妨试试 stripplot warnings.warn(msg, UserWarning)

    要获得您想要的情节,请改用stripplot

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    import seaborn as sns
    
    data = pd.DataFrame(np.random.rand(5, 2), columns=['A', 'B'])
    
    f, ax = plt.subplots(1, 2, figsize=(8, 8))
    sns.barplot('A', 'B', data=data, ax=ax[0])
    sns.stripplot('A', 'B', data=data, ax=ax[1])
    plt.show()
    

    【讨论】:

    • 感谢@JE_Muc,我检查了参考资料,似乎pointplotfactorplotstripplot 更相似。感谢您的提示!
    • @Ben 欢迎您,如果对您有帮助,也可以投票/接受我的回答。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 2012-03-13
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多