【问题标题】:how to get different line colors depending on one variable for different plots in one single figure in python? [duplicate]python - 如何根据python中一个图形中不同图的一个变量获得不同的线条颜色? [复制]
【发布时间】:2021-07-08 09:18:42
【问题描述】:

假设我有一个带有一定数量地块的图形,类似于这个:

其中单个图的颜色由 matplotlib 自动决定。获取这个的代码很简单:

for i in range(len(some_list)):
    x, y = some_function(dataset, some_list[i])
    plt.plot(x, y) 

现在假设所有这些行都依赖于第三个变量 z。我想包含这些信息,用一种颜色绘制给定的线,该颜色提供有关 z 大小的信息,可能使用图右侧的颜色图和颜色条。你会建议我做什么?我排除使用图例,因为在我的图中我有更多的线条,而不是我展示的线条。我能找到的所有信息都是关于如何用不同颜色绘制一条线,但这不是我想要的。提前谢谢你!

【问题讨论】:

    标签: python matplotlib plot data-visualization figure


    【解决方案1】:

    这里有一些代码,在我看来,你可以很容易地适应你的问题

    import numpy as np
    import matplotlib.pyplot as plt
    from random import randint
    
    # generate some data
    N, vmin, vmax = 12, 0, 20
    rd = lambda: randint(vmin, vmax)
    segments_z = [((rd(),rd()),(rd(),rd()),rd()) for _ in range(N)]
    
    # prepare for the colorization of the lines,
    # first the normalization function and the colomap we want to use
    norm = plt.Normalize(vmin, vmax)
    cm = plt.cm.rainbow
    # most important, plt.plot doesn't prepare the ScalarMappable
    # that's required to draw the colorbar, so we'll do it instead
    sm = plt.cm.ScalarMappable(cmap=cm, norm=norm)
    
    # plot the segments, the segment color depends on z
    for p1, p2, z in segments_z:
        x, y = zip(p1,p2)
        plt.plot(x, y, color=cm(norm(z)))
    
    # draw the colorbar, note that we pass explicitly the ScalarMappable
    plt.colorbar(sm)
    
    # I'm done, I'll show the results,
    # you probably want to add labels to the axes and the colorbar.
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2015-10-07
      • 2011-06-15
      • 1970-01-01
      • 1970-01-01
      • 2013-06-18
      • 1970-01-01
      相关资源
      最近更新 更多