简体   繁体   English

在一个图中并排绘制多个图形

[英]Plotting multiple graphs side-by-side in one figure

I have made multiple histograms using the following generalised snippet of code (mdified sligtly for each one):我使用以下通用代码片段制作了多个直方图(对每个直方图进行了轻微修改):

import matplotlib.pyplot as plt

plt.hist(df['count'], color = 'blue', edgecolor = 'black', bins = int(12/1))
plt.title('Histogram')
plt.xlabel('No. of individuals')
plt.ylabel('No. of images')

As it stands, I'm having to run this code as 8 different commands, to produce 8 seperate histograms.就目前而言,我必须将此代码作为 8 个不同的命令运行,以生成 8 个单独的直方图。 How therefore can I plot all 8 graphs as a single figure, with the individual plots set side-by-side?因此,如何将所有 8 个图形绘制为一个图形,并将各个图形并排设置?

Is this possible?这可能吗?

Thanks, R谢谢,R

So in order to address the issue, I will show you the way to solve for 3 different histograms on the same plot, the same logic can be applied to any k number of histograms.因此,为了解决这个问题,我将向您展示在同一图上求解 3 个不同直方图的方法,相同的逻辑可以应用于任意k个直方图。

import numpy as np
import matplotlib.pyplot as plt

n = 5000
mean_mu1 = 60
sd_sigma1 = 15
data1 = np.random.normal(mean_mu1, sd_sigma1, n)
mean_mu2 = 80
sd_sigma2 = 15
data2 = np.random.normal(mean_mu2, sd_sigma2, n)
mean_mu3 = 100
sd_sigma3 = 15
data3 = np.random.normal(mean_mu3, sd_sigma3, n)

plt.figure(figsize=(8,6))
plt.hist(data1, bins=100, alpha=0.5, label="data1")
plt.hist(data2, bins=100, alpha=0.5, label="data2")
plt.hist(data3, bins=100, alpha=0.5, label="data3")
plt.xlabel("Data", size=14)
plt.ylabel("Count", size=14)
plt.title("Multiple Histograms with Matplotlib")
plt.legend(loc='upper right')
plt.savefig("overlapping_histograms_with_matplotlib_Python_2.png")

This will generate the following:这将生成以下内容:

在此处输入图片说明

Source: https://datavizpyr.com/overlapping-histograms-with-matplotlib-in-python/来源: https : //datavizpyr.com/overlapping-histograms-with-matplotlib-in-python/

Note笔记

This kind of plot will be very difficult to read when you deal with 8 different histograms.当您处理 8 个不同的直方图时,这种图将很难阅读。

Edit编辑

Based on the comment, you wish to plot k different histograms in 1 big figure.根据评论,您希望在 1 个大图中绘制k不同的直方图。

I'll show the logic to do so with 4 different histograms:我将用 4 个不同的直方图展示这样做的逻辑:

import numpy as np
import matplotlib.pyplot as plt

n = 5000
mean_mu1 = 60
sd_sigma1 = 15
data1 = np.random.normal(mean_mu1, sd_sigma1, n)
mean_mu2 = 80
sd_sigma2 = 15
data2 = np.random.normal(mean_mu2, sd_sigma2, n)
mean_mu3 = 100
sd_sigma3 = 15
data3 = np.random.normal(mean_mu3, sd_sigma3, n)
mean_mu4 = 120
sd_sigma4 = 15
data4 = np.random.normal(mean_mu4, sd_sigma4, n)
data = [data1, data2, data3, data4]
f, a = plt.subplots(2,2)
a = a.ravel()
for idx, ax in enumerate(a):
    ax.hist(data[idx])

plt.show()

This will output the following:这将输出以下内容:

在此处输入图片说明

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

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