代码之家  ›  专栏  ›  技术社区  ›  user98235

在Matplotlib中绘制不同颜色的图形

  •  0
  • user98235  · 技术社区  · 8 年前

    我有下表。

      Date       Score
    11-01-02      40
    11-01-03      47
    11-01-04      41
    11-01-05      35
    11-01-06      52
    11-01-07      47
    11-01-08      45
    11-01-09      43
    11-01-10      40
    11-01-11      41
    11-01-12      41
    11-01-13      49
    11-01-14      40
    11-01-15      40
    

    我把它作为python中的pandas文件来读,我想把它画成一个线图,这样2011/01/08之前的分数都是黄色的,而2011/01/08或之后的分数都是红色的。

    在python中是可能的吗?我知道在R语言中怎么做,但我不确定熊猫是否有类似的功能。

    2 回复  |  直到 8 年前
        1
  •  1
  •   Anton vBR    8 年前

    import pandas as pd
    import matplotlib.pyplot as plt
    
    csvdata = '''\
    Date          Score
    11-01-02      40
    11-01-03      47
    11-01-04      41
    11-01-05      35
    11-01-06      52
    11-01-07      47
    11-01-08      45
    11-01-09      43
    11-01-10      40
    11-01-11      41
    11-01-12      41
    11-01-13      49
    11-01-14      40
    11-01-15      40'''
    
    # Recreate data and convert Date to datetime
    fileobj = pd.compat.StringIO(csvdata)
    df = pd.read_csv(fileobj, sep='\s+')
    df['Date'] = pd.to_datetime(df['Date'], yearfirst=True)
    
    # Based on the date provided by OP, either RED or YELLOW to col Color
    cond = df.Date >= '2011-01-08'
    df['Color'] = np.where(cond, 'RED', 'YELLOW')
    
    # Create the frame 
    fig, ax = plt.subplots(figsize=(8,6))
    
    # Fill the frame with data (note: missing datapoint!)
    for color, dfx in df.groupby('Color'):
       dfx.plot(x='Date', y='Score', color=color, ax=ax) 
    
    # The workaround --> does not feel reliable for consistant use though.
    m1 = df['Date'].between('2011-01-07', '2011-01-08')
    df[m1].plot(x='Date',y='Score', color=df['Color'], ax=ax)
    
    plt.show()
    

    enter image description here

        2
  •  2
  •   Mr. T Andres Pinzon    8 年前