我有一组数据,我可以从中生成3个图(参见示例)。顶部图是从一个完整集创建的,另一个是从子集创建的。
我想看到的是第二和第三个图中的线是连续的。怎么做到这一点?下面是https://scipy-cookbook.readthedocs.io/items/Matplotlib_Plotting_values_with_masked_arrays.html的修改示例
import numpy as np
import matplotlib.pyplot as plt
# suppose we have full serie of y values and 2 others that can have gaps
# but always one is available like:
# y: 10, 20, 30, 40 , 50
# y2: 1, 4, -, - , 12
# y3: -, -, 6, 8 , -
y_values = [92,94,100,97,98,102,99,101,97,102,99,105,101]
# prepare for masking arrays - 'conventional' arrays won't do it
y_values = np.ma.array(y_values)
# from y artifically create y2 and y2
# give a threshold
threshold = 99
y2_values = np.ma.masked_where(y_values < threshold, [v-50 for v in y_values])
y3_values = np.ma.masked_where(~(y_values < threshold), [v-80 for v in y_values])
x_values = [0,1,2,3,4,5,6,7,8,9,10,11,12]
fig, ax = plt.subplots(3, sharex=True, facecolor='w')
fig.subplots_adjust(hspace=0.25)
#plot all data
ax[0].plot(x_values, y_values) #,'ko')
ax[0].set_title('All values')
ax[1].plot(x_values, y2_values) #,'ko')
ax[1].set_title('y2-values')
#ax = plt.subplot(313)
ax[2].plot(x_values, y3_values) #,'ko')
ax[2].set_title('y3-values')
fig.savefig("3sp.png")
您可以将绘图限制为未屏蔽的值。也就是说,而不是绘图
[-- -- 50 -- -- 52 49 51 -- 52 49 55 51]
你可以绘图
[50 52 49 51 52 49 55 51]
这可以通过过滤mask
本身来完成。
ax.plot(x_values[~y2_values.mask], y2_values[~y2_values.mask])
完整的例子:
import numpy as np
import matplotlib.pyplot as plt
y_values = [92,94,100,97,98,102,99,101,97,102,99,105,101]
y_values = np.ma.array(y_values)
threshold = 99
y2_values = np.ma.masked_where(y_values < threshold, [v-50 for v in y_values])
y3_values = np.ma.masked_where(~(y_values < threshold), [v-80 for v in y_values])
x_values = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12])
fig, ax = plt.subplots(3, sharex=True, facecolor='w')
fig.subplots_adjust(hspace=0.25)
ax[0].plot(x_values, y_values, marker="o")
ax[0].set_title('All values')
ax[1].plot(x_values[~y2_values.mask], y2_values[~y2_values.mask], marker="o")
ax[1].set_title('y2-values')
ax[2].plot(x_values[~y3_values.mask], y3_values[~y3_values.mask], marker="o")
ax[2].set_title('y3-values')
plt.show()