【问题标题】:Matplotlib simple different colour lines graph [duplicate]Matplotlib简单的不同颜色线图[重复]
【发布时间】:2019-11-29 13:27:54
【问题描述】:

我有一个非常简单的 matplot 图,想要更改线条颜色,当数据高于 50 时,线条将变为红色,低于 50 时,线条颜色将变为绿色。

如何更改线条颜色,目前我使用绘图加载 x 和 y 数据然后显示图表。

我尝试了两种将数据加载到图表中的方法,但它们都不起作用,也无法弄清楚我们在处理看似如此简单的事情时要做什么。

# ==========================
# First try at the changing the line colour

import matplotlib.pyplot as plt
import pandas as pd

for i in range(0,100):
   if (i>50):
       plt.plot(i,i, color = 'r') #plot red line
if (i<49):
    plt.plot(i,i, color = 'g') #plot red line

plt.show()

# ==========================
# Second try at the changing the line colour

for i in range(0,50):
   x.append(i)
   y.append(i)

plt.plot(x,y, color='green')

for i in range(50,100):
   x.append(i)
   y.append(i)

plt.plot(x,y, color='red')
plt.show()

【问题讨论】:

    标签: python matplotlib graph


    【解决方案1】:

    最简单的解决方案是绘制两条线,一条绿色,一条红色。您的第二次尝试接近于这样做,问题是您的红线;你用绿色绘制 0-50,然后用红色绘制 0-100(你一直在追加而没有先清除列表!)

    如果你使用 numpy 数组,那么使用条件切片来生成你想要的数据元素真的很容易。试试这个:

    import numpy as np
    x = np.arange(100)
    y = np.arange(100)
    
    # Plot all data elements in red
    plt.plot(x, y, color='red')
    
    # Replot any y<50 elements in green
    plt.plot(x[y < 50], y[y < 50], color='green')
    
    plt.show()
    

    由于第二个图是第一个图的子集,因此您会得到隐藏红点的绿点。这在视觉上等同于仅分别绘制红点和绿点,例如通过使用 plt.plot(x[y &gt;= 50], y[y &gt;= 50], color='red') 仅绘制 >= 50 个元素

    【讨论】:

      【解决方案2】:

      分别绘制一条线的每一部分。

      import numpy as np
      x = np.linspace(0,100,100)
      y = x
      
      plt.plot(x[:50], y[:50],'r')
      plt.plot(x[50:], y[50:], 'g')
      plt.show()
      

      在你的情况下,它会是

      i = range(50)
      plt.plot(i,i, color = 'r') #plot red line
      i = range(50, 100)
      plt.plot(i,i, color = 'g') #plot red line
      
      plt.show()
      

      【讨论】:

        【解决方案3】:

        第一个代码:您的第一个代码不起作用的原因是您试图在 for 循环中将 单个点 绘制为线。这行不通。相反,在这个 for 循环中起作用的是散点图或标记图。您可以通过指定标记类型来实现此目的,例如 o 以显示点。您可以使用markersize 控制标记的大小,如下代码所示:

        for i in range(0,100):
            if (i>50):
                plt.plot(i,i, 'o',color = 'r', markersize=2) #plot red dots
            if (i<49):
                plt.plot(i,i, 'o',color = 'g', markersize=5) #plot green dots
        

        第二个代码:第二个代码不起作用的原因是您使用相同的列表来附加数据。所以第二条线(红线)与第一条线重叠。如果您将空列表重新初始化为,则第二种解决方案将起作用

        x, y = [], []
        
        for i in range(0,50):
            x.append(i)
            y.append(i)
        
        plt.plot(x,y, color='green')
        
        x, y = [], [] # Re-initialize the lists
        for i in range(50,100):
            x.append(i)
            y.append(i)
        
        plt.plot(x,y, color='red')
        

        【讨论】:

          猜你喜欢
          • 2018-05-21
          • 1970-01-01
          • 2023-03-14
          • 1970-01-01
          • 1970-01-01
          • 2013-04-07
          • 1970-01-01
          • 2015-05-23
          相关资源
          最近更新 更多