首页 > 解决方案 > 如何用两种不同的颜色绘制一条曲线?(不使用熊猫)

问题描述

我需要创建一个图表,使用matplotlib.pyplot它显示地球和火星之间的距离随时间的变化。除此之外,某些月份(例如 3 月至 8 月)应以与其他月份不同的颜色显示。数据由包含日期、距离以及指示日期是否在 3 月到 8 月跨度内的标志的数组提供。

包含整个数据的数组称为master_array。第一列包含日期,第二列包含距离;第七个 s/w 标志。('s' 代表夏天,'w' 代表冬天)。

我试图利用这样一个事实,即为pyplot.plot每个.plot命令切换颜色,我首先绘制冬季月份,然后再绘制夏季月份。

import numpy as np
from matplotlib import pyplot as plt

def md_plot2(dt64=np.array, md=np.array):
    """Erzeugt Plot der Marsdistanz (y-Achse) zur Zeit (x-Achse)."""
    plt.style.use('seaborn-whitegrid')

    y, m, d = dt64.astype(int) // np.c_[[10000, 100, 1]] % np.c_[[10000, 100, 100]]
    dt64 = y.astype('U4').astype('M8') + (m-1).astype('m8[M]') + (d-1).astype('m8[D]')

    wFilter = np.argwhere(master_array[:,6] == 0)
    sFilter = np.argwhere(master_array[:,6] == 1)

    plt.plot(dt64[wFilter], md[wFilter], label='Halbjahr der fallenden \nTemperaturen')
    plt.plot(dt64[sFilter], md[sFilter], label='Halbjahr der steigenden \nTemperaturen')

    plt.xlabel("Zeit in Jahren\n")
    plt.xticks(rotation = 45)
    plt.ylabel("Marsdistanz in AE\n(1 AE = 149.597.870,7 km)")
    plt.legend(loc='upper right', frameon=True)

plt.figure('global betrachtet...') # diesen Block ggf. auskommentieren
#plt.style.use('seaborn-whitegrid')
md_plot2(master_array[:,0], master_array[:,1]) # Graph

plt.show()
#plt.close()

现在的问题是,在夏季的最后一个点和下一个夏季的第一个点之间,夏季的图显示了一条线,而另一个图(冬季)显示了介于这两个夏季之间的冬季的正确数据。数据包含许多数据点,这将导致这两种颜色的许多段。当下一个数据点在未来一天以上时,如何停止绘图以绘制一条线?这项任务是否有另一种方法pyplot

当我在不使用熊猫的情况下在属于它的脚本中编写了很多代码时,我很高兴找到一个不使用熊猫的解决方案,因为我试图避免它,因为我不想让我的脚本膨胀一种通过使用我已经在使用的模块完成任务的方法。我还读到它会降低这里的速度。

标签: pythonpython-3.xnumpymatplotlibplot

解决方案


multicolored_line示例看起来像你想要的。

有关 Matplotlib 中颜色图系统的更多信息,另请参阅本文。


推荐阅读