gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:35:16 26 4
gpt4 key购买 nike

我想为多个数组创建直方图,这些数组将共享百分比 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com