我有两个列表:数据和given_x_axis
data=[[0.05, 3200], [0.1, 2000], [0.12, 1200], [0.13, 2000], [0.21, 1800], [0.25, 2800], [0.27, 1500]]
given_x_axis=[0.05, 0.07, 0.09, 0.11, 0.13, 0.15, 0.17, 0.19, 0.21, 0.23, 0.25, 0.27, 0.29, 0.31, 0.33, 0.35]
我想绘制步骤图,像这样累积总和,
x,y=map(list, zip(*np.cumsum(data, axis=0)))
plt.step(x,y)
但使用given_x_axis代替作为x轴的步骤
我曾试图定义,再现基础上,given_x_axis累计值的一个新的列表功能
def update_x_axis(data, given_x_axis):
cumulated_values=[]
value_each_step=0
for n,x in enumerate(given_x_axis):
for d in data:
if d[0]<=x:
value_each_step=value_each_step+d[1]
cumulated_values.append(value_each_step)
return [given_x_axis,cumulated_values]
但是累计值的上y轴的新名单似乎并不正确。我希望update_x_axis(数据,given_x_axis)将返回
[0.05, 0.07, 0.09, 0.11, 0.13, 0.15, 0.17, 0.19, 0.21, 0.23, 0.25, 0.27, 0.29, 0.31, 0.33, 0.35],
[3200, 3200, 3200, 5200, 6400, 8400....]]
如何修改我的定义函数来做到这一点?
我可能误解了问题或所期望的结果。我想你要找的是这样的:
import numpy as np
import matplotlib.pyplot as plt
data=[[0.05, 3200], [0.1, 2000], [0.12, 1200], [0.13, 2000], [0.21, 1800], [0.25, 2800], [0.27, 1500]]
given_x_axis=[0.05, 0.07, 0.09, 0.11, 0.13, 0.15, 0.17, 0.19, 0.21, 0.23, 0.25, 0.27, 0.29, 0.31, 0.33, 0.35]
x,y = np.array(data).T
ind = np.searchsorted(x, given_x_axis, side="left")
ind[ind == 0] = 1
res = np.cumsum(y)[ind-1]
水库是现在
[ 3200. 3200. 3200. 5200. 6400. 8400. 8400. 8400. 8400. 10200.
10200. 13000. 14500. 14500. 14500. 14500.]
然后绘图,
fig, ax = plt.subplots()
ax.plot(x,np.cumsum(y), marker="o", ls="")
ax.step(given_x_axis, res)
plt.show()