繁体   English   中英

如何使用 python 在一张图中显示多个 Matplotlib?

[英]how to show multiple Matplotlib in one figure using python?

我有一个 python 脚本,plot直方图wordcloud在 2 个单独的图中。

我想要的是 plot 这两个结果合二为一。

代码:

#plot word count distribution for both positive and negative sentiment
x= def_test_twtr_preds["processed word count"][def_test_twtr_preds.predictions ==1]
y= def_test_twtr_preds["processed word count"][def_test_twtr_preds.predictions ==0]
fig1 = plt.figure(figsize=(12,6))
plt.xlim(0,45)
plt.xlabel("word count")
plt.ylabel("frequency")
g = plt.hist([x,y],color=["r","b"],alpha=0.5,label=["positive","negative"])
plt.legend(loc="upper left")

# splt sentence to get individual words
all_words=[]
for line in def_test_twtr_preds["tokens"]: 
    all_words.extend(line)

#create a word frequency dictionary
wordfreq = Counter(all_words)

# #draw a word cloud with word frequencies
wordcloud = WordCloud(width=900,
                     height = 500,
                     max_words=500,
                     max_font_size=100,
                     relative_scaling=0.5,
                     colormap="Blues",
                     normalize_plurals=True).generate_from_frequencies(wordfreq)


fig2 = plt.figure(figsize=(17,14))
plt.imshow(wordcloud,interpolation="bilinear")
plt.axis("off")
plt.show()

为此,您可以使用matplotlib 中的 subplot方法 看看这个“图 1”是如何生成的https://matplotlib.org/3.1.1/gallery/subplots_axes_and_figures/multiple_figs_demo.html

对于更复杂的子图,请查看子图文档https://matplotlib.org/devdocs/gallery/subplots_axes_and_figures/subplots_demo.html

我希望这有帮助。

我无法完全重写您的代码,因为它似乎有很大一部分丢失了,但是像这样重写绘图部分应该可以解决问题:

fig = plt.figure(figsize=(30,30)) # Change to whichever size you want
ax1 = plt.subplot(121)
ax1.set_xlim(0,45)
ax1.set_xlabel("word count")
ax1.set_ylabel("frequency")
g = ax1.hist([x,y],color=["r","b"],alpha=0.5,label=["positive","negative"])
plt.legend(loc="upper left")

# splt sentence to get individual words
all_words=[]
for line in def_test_twtr_preds["tokens"]: 
    all_words.extend(line)

#create a word frequency dictionary
wordfreq = Counter(all_words)

# #draw a word cloud with word frequencies
wordcloud = WordCloud(width=900,
                     height = 500,
                     max_words=500,
                     max_font_size=100,
                     relative_scaling=0.5,
                     colormap="Blues",
                     normalize_plurals=True).generate_from_frequencies(wordfreq)


ax2 = plt.subplot(122)
ax2.imshow(wordcloud,interpolation="bilinear")
plt.show()

见@leo-aimone 的

暂无
暂无

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

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