python - 如何使用 matplotlib 创建具有不同长度的多个数组的直方图,其中 y 轴上有百分比

标签 python matplotlib

我想为多个数组创建直方图,这些数组将共享百分比 y 轴。

例如,正确绘制此图:

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker

# these are my measurements, unsorted
num_of_points = 10000
num_of_bins = 20
data = np.random.randn(num_of_points) # generate random numbers from a gaussian distribution
fig, ax = plt.subplots()
ax.hist(data, bins=num_of_bins, edgecolor='black', alpha=0.3)
ax.set_title("Histogram")
ax.set_xlabel("X axis")
ax.set_ylabel("Percentage")
ax.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=len(data)))
plt.show()

Figure 1

但是当我添加另一个具有不同长度的数据时,data2 的百分比关闭,因为 PercentFormatter 采用 len(data)。

num_of_points = 10000
num_of_points2 = 30000
num_of_bins = 20
data = np.random.randn(num_of_points) # generate random numbers from a gaussian distribution
data2 = np.random.randn(num_of_points2) 
fig, ax = plt.subplots()
ax.hist(data, bins=num_of_bins, edgecolor='black', alpha=0.3)
ax.hist(data2, bins=num_of_bins, edgecolor='black', alpha=0.3)
ax.set_title("Histogram")
ax.set_xlabel("X axis")
ax.set_ylabel("Percentage")
ax.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=len(data2)))
plt.show()

Figure 2

那么我怎样才能共享 y-ax 百分比,这对于两个数据数组都是正确的?

最佳答案

我认为解决此问题的一种方法是使用辅助 y 轴绘制第二个数据。

试试这个!

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker

# these are my measurements, unsorted
num_of_points = 10000
num_of_bins = 20
data = np.random.randn(num_of_points) # generate random numbers from a gaussian distribution
fig, ax = plt.subplots()
ax.hist(data, bins=num_of_bins, color='blue', edgecolor='black', alpha=0.1)
ax.set_title("Histogram")
ax.set_xlabel("X axis")
ax.set_ylabel("Percentage of data")
ax.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=len(data)))

ax1 = ax.twinx()
num_of_points2 = 30000
data2 = np.random.randn(num_of_points2) 
ax1.hist(data2, bins=num_of_bins, color='orange', edgecolor='black', alpha=0.1)
ax1.set_ylabel("Percentage of data2")
ax1.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=len(data2)))
plt.show()

关于python - 如何使用 matplotlib 创建具有不同长度的多个数组的直方图,其中 y 轴上有百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53277868/

相关文章:

python - 计算 Pandas 数据框中的新列

Python:如何获取一个用户名的组 id(如 id -Gn )

python - 我可以从笔记本重启 iPython 集群吗?

python - python中的圆形/极坐标直方图

python - matplotlib.pylab.hist 中的 histt​​ype ='bar'/'stepfilled'/'barstacked' 之间有什么区别?

python - 将 x 轴刻度更改为自定义字符串

python-2.7 - 使用循环绘制 n 个图表 Python

python - 在 python 中导入文件与运行该文件一样吗?

python - 随着时间的推移可视化多个虚拟变量

python - 通过python复制excel行