matplotlib 在Python中绘制由概率密度组成的人口金字塔

lmvvr0a8  于 2023-10-24  发布在  Python
关注(0)|答案(1)|浏览(204)

我试图绘制一个像this这样的人口金字塔。然而,我不仅仅想要直方图,我还想要概率密度(密度之和应该是1)。当我使用matplotlib分别绘制它们时,这很容易。但是我无法使用类似的代码来获得人口金字塔。下面是我使用matplotlib绘制直方图的MWE-

import numpy as np
import matplotlib.pyplot as plt
X = np.arange(1000)

Y = np.arange(1100)

# Define the bin size and bins
bin_size = 150  # Adjust the bin size as needed
bins = np.arange(0, max(max(X), max(Y)) + bin_size, bin_size)

fig, axs = plt.subplots(2, 1, sharey=True, sharex=True)

# Plot the histogram for X
axs[0].hist(X, bins=bins, color='black',  rwidth=0.7, density=True)

# Plot the histogram for Y
axs[1].hist(Y, bins=bins, color='darkgrey', rwidth=0.7, density=True)

# Set title and labels for each subplot
axs[0].set_title('Distribution of X')
axs[1].set_title('Distribution of Y')

axs[1].set_xlabel('Duration (s)')  # Set xlabel only for the bottom subplot
axs[0].set_ylabel('Probability Density')
axs[1].set_ylabel('Probability Density')

# Set the y-axis to be logarithmic for each subplot
axs[0].set_yscale("log")
axs[1].set_yscale("log")

# Adjust spacing and show the plot
plt.tight_layout()
plt.show()
flmtquvp

flmtquvp1#

我建议使用np.histogram来计算概率密度。有了这些,你可以使用一个类似于问题中的代码来使用seaborn绘制人口金字塔。下面是我的方法:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

X = np.arange(1000)
Y = np.arange(1100)

bin_size = 150
bins = np.arange(0, max(X.max(), Y.max()) + bin_size, bin_size)

df = pd.DataFrame({
    "bins": [f"{bin_start}–{bin_end} s" for bin_start, bin_end in zip(bins[:-1], bins[1:])],
    "X": -np.histogram(X, bins, density=True)[0],
    "Y": np.histogram(Y, bins, density=True)[0],
})

fig, ax = plt.subplots(figsize=(8, 4))

sns.barplot(df, x="X", y="bins", order=df["bins"][::-1], ax=ax, color="black")
sns.barplot(df, x="Y", y="bins", order=df["bins"][::-1], ax=ax, color="darkgrey")

ax.set_title("Population pyramid with densities")
ax.set_xlabel("Distribution of -X and Y")
ax.set_ylabel("Duration bins")

fig.tight_layout()
plt.show()

这段代码产生以下结果:

相关问题