【问题标题】:How to change the line colour for different lines in a subplot如何更改子图中不同线条的线条颜色
【发布时间】:2013-09-16 21:04:46
【问题描述】:

我希望能够将线条的颜色更改为我使用 matplotlib 在绘图上指定的颜色。

下面是我正在使用的相关代码(它是函数的一部分)。变量avg_rel_track是一个“二维数组”,每一列对应一个“刀片”。每个“刀片”都绘制一条单独的线。

我希望每个刀片/线条都是我指定的颜色。我正在努力寻找相关文档,如果很明显,我很抱歉。

 def plot_data(avg_rel_track, sd_rel_track_sum, shade):

    fig = plt.figure(figsize=(18,10))

    gs  = gridspec.GridSpec(5, 1, height_ratios=[1.75, 1 ,1, 1])
    ax0 = plt.subplot(gs[0])
    ax1 = plt.subplot(gs[1])
    ax2 = plt.subplot(gs[2])
    ax3 = plt.subplot(gs[3])
    ax4 = plt.subplot(gs[4])

    fig.subplots_adjust(top=0.93)

    #The following plot has 5 plots within it.
    lineObjects = ax0.plot(avg_rel_track_nan)
    ax0.set_title('Averaged Relative Track',fontsize=11)
    ax0.legend(lineObjects, (1,2,3,4,5),loc='lower center', bbox_to_anchor=(0.82, 1),
      fancybox=True, shadow=True, ncol=5)

下面是一个情节示例(非常粗糙)我想将情节更改为我指定的情节。它是 5 个子地块中的一个作物

【问题讨论】:

    标签: python matplotlib plot line


    【解决方案1】:

    问题是plot 函数只接受一种颜色作为参数。因此,您必须遍历列并分别绘制每一列。

    columns = [[1,2,3],[1,4,5],[6,4,2]]
    colors = ['green', 'pink', 'blue']
    labels = ['foo', 'bar', 'baz']
    
    fig, ax = plt.subplots(1, 1)
    for i, column in enumerate(columns):
        ax.plot(column, color=colors[i], label=labels[i])
    ax.legend(loc='lower center', bbox_to_anchor=(0.82, 1),
              fancybox=True, shadow=True, ncol=3)
    

    【讨论】:

    • 嗨,维克多,感谢您的帮助。我目前有这个:` colours=['red', 'black', 'grey', 'yellow','blue'] labels=['1','2','3','4','5 '] for i, column in enumerate(avg_rel_track_nan): ax0.plot(column, colours[i], label=labels[i])` 我得到索引超出范围的错误?
    • @AshleighClayton 在ax0.plot(column, colours[i], .. 行中,您将colours[i] 绘制为y 数据,绘图将前两个参数作为x 和y 数据。你需要ax0.plot(column, color=colours[i]..。
    • @AshleighClayton 是的,我的错误,我忘了添加关键字参数。固定。
    • 你也可以和colorcycle一起玩,达到同样的效果
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多