从给定的 NumPy 文件绘制洛伦兹曲线

Plotting a Lorenz curve from a given NumPy file

我正在尝试编写一个程序,从 NumPy 文件中读取数据,然后使用该数据绘制洛伦兹曲线,但我不确定如何制作洛伦兹曲线。我尝试使用 cumsum() 函数,但无法绘制洛伦兹曲线。这是我目前所拥有的:

import numpy as np
import matplotlib.pyplot as plt

data = np.load('pop2010.npy')
print(data)
plt.plot(data[0]) # display all the points
plt.show()

plot_x = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
plot_y = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

plt.plot(plot_x, plot_y)

# set the labels for x, y, and title
plt.xlabel("Countries")
plt.ylabel("Wealth")
plt.title("Population-Lorenz Curve") 

# save plot as png file
plt.savefig('population-lorenz.png', dpi = 200)
plt.show()

如有任何建议,将不胜感激!

改编自 https://zhiyzuo.github.io/Plot-Lorenz/,结合您的代码。

从你提供的上下文来看不太清楚,但我认为 data 是你想要绘制的洛伦兹曲线,plot_x, plot_y 变量是你绘制 x-y行?

请注意,我使用的是 object-oriented API 而不是 pyplot API 因为这是文档现在推荐的内容——我想您会发现在长 运行 中使用起来更容易。有关详细信息,请参阅 https://matplotlib.org/stable/api/index.html#usage-patterns

import numpy as np
import matplotlib.pyplot as plt

data = np.load('pop2010.npy')

X_lorenz = data.cumsum() / data.sum()
X_lorenz = np.insert(X_lorenz, 0, 0)

fig, ax = plt.subplots(figsize=[6,6])
## scatter plot of Lorenz curve
ax.scatter(np.arange(X_lorenz.size)/(X_lorenz.size-1), X_lorenz, 
           marker='x', color='darkgreen', s=100)
## line plot of equality
ax.plot([0,1], [0,1], color='k')


# set the labels for x, y, and title
ax.set_xlabel("Countries")
ax.set_ylabel("Wealth")
ax.set_title("Population-Lorenz Curve") 

plt.show()

# save plot as png file
plt.savefig('population-lorenz.png', dpi = 200)