【问题标题】:Subplot two graph plotting in two differents functions matplotlib在两个不同的函数 matplotlib 中绘制两个图的子图
【发布时间】:2018-12-15 17:40:09
【问题描述】:

我在任何地方都找不到如何用不同的函数绘制两个相邻的图。任何人都可以帮助我吗?我使用 Jupyter Notebook。

第一个函数:

def OccurrenciesPlotting(filtered_sent):
    fdist = FreqDist(filtered_sent)      
    fdist.plot(40,cumulative=False)

第二个功能:

def MyWordCloud(filtered_sent):
    img  = np.array(Image.open("H....jpg")) 
    stopwords = set(STOPWORDS)
    .
    .
    .

    image_colors = ImageColorGenerator(img)

    plt.figure()
    plt.imshow(wordcloud.recolor(color_func=image_colors),
               interpolation="bilinear")
    plt.axis("off")
    plt.savefig('wordcloud.png', format="png")
    plt.show()

我希望函数的结果一个挨着另一个

非常感谢:)

【问题讨论】:

    标签: python matplotlib plot jupyter-notebook subplot


    【解决方案1】:

    要绘制子图,您必须使用 plt.subplots() 函数。然后,您的图形就是包含两个子图的图形,并且每个子图都位于一个轴对象上。 由于您的代码不可重现,由于我们缺乏数据,我无法为您提供完整的代码。 通常,您应该将希望函数绘制的轴作为参数传递。 将熊猫导入为 pd 将 matplotlib.pyplot 导入为 plt

    df = pd.DataFrame({"a":[1,2,3], "b": [2,3,4]})
    
    def f1(df, axis):
        return df["a"].plot(ax = axis)
    
    def f2(df, axis):
        axis = plt.plot(df["b"], c = "g")
        return axis
    
    fig, axes = plt.subplots(nrows =1, ncols = 2)
    f1(df, axes[0])
    axes[1] = f2(df, axes[1])
    plt.show()
    

    如您所见,在使用 pandas 绘图函数和 matplotlibs 函数时,您必须使用稍微不同的方法。您可以使用 ax 参数将所需的轴传递给 df.plot()。为了使用常规的 matplotlib 库,我从函数中返回了一个轴对象。

    【讨论】:

      猜你喜欢
      • 2021-03-12
      • 2013-04-27
      • 1970-01-01
      • 2020-03-03
      • 2013-01-31
      • 2019-09-03
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      相关资源
      最近更新 更多