【问题标题】:half yearly colorbar in matplotlib and pandasmatplotlib 和 pandas 中的半年彩条
【发布时间】:2017-12-07 09:29:49
【问题描述】:

我有一个熊猫数据框。我正在制作散点图并尝试根据颜色条对数据进行分类。我这样做是为了每月分类和质量分类,如下面的示例代码所示。

a = np.random.rand(366)
b = np.random.rand(366)*0.4
index = (pd.date_range(pd.to_datetime('01-01-2000'), periods=366))
df = pd.DataFrame({'a':a,'b':b},index = index)
plt.scatter(df['a'],df['b'],c = df.index.month)
plt.colorbar()

还有质量:

plt.scatter(df['a'],df['b'],c = df.index.quarter)
plt.colorbar()

我的问题:有没有办法按半年分类。例如从 1-6 和 7-12 月份开始,也可以按月份:10-3 和 4-9 谢谢您,您的帮助/建议将不胜感激。

【问题讨论】:

    标签: python pandas matplotlib datetimeindex


    【解决方案1】:

    我会选择不会完全截断每月信息的解决方案。使用月份相似但可区分的颜色可以直观地按半年和月份进行分类。

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.colors
    
    a = np.random.rand(366)
    b = np.random.rand(366)*0.4
    index = (pd.date_range(pd.to_datetime('01-01-2000'), periods=366))
    df = pd.DataFrame({'a':a,'b':b},index = index)
    
    colors=["crimson", "orange", "darkblue", "skyblue"]
    cdic = list(zip([0,.499,.5,1],colors))
    cmap = matplotlib.colors.LinearSegmentedColormap.from_list("name", cdic,12 )
    norm = matplotlib.colors.BoundaryNorm(np.arange(13)+.5,12)
    
    plt.scatter(df['a'],df['b'],c = df.index.month, cmap=cmap, norm=norm)
    plt.colorbar(ticks=np.arange(1,13))
    
    plt.show()
    

    【讨论】:

      【解决方案2】:

      制作一个自定义函数以将散点函数放入颜色参数。我举了一个半年划分的例子。您可以将其用作您自己的拆分功能的模板:

      import numpy as np
      import pandas as pd
      import matplotlib.pylab as plt
      
      # if month is 1 to 6 then the first halfyear else the second halfyear 
      def halfyear(m):
          return 0 if (m <= 6) else 1
      # vectorize function to use with Series
      hy = np.vectorize(halfyear)
      
      a = np.random.rand(366)
      b = np.random.rand(366)*0.4
      index = (pd.date_range(pd.to_datetime('01-01-2000'), periods=366))
      df = pd.DataFrame({'a':a,'b':b},index = index)
      
      # apply custom function 'hy' for 'c' argument
      plt.scatter(df['a'],df['b'], c = hy(df.index.month))
      plt.colorbar()
      
      plt.show()
      

      另一种使用 lambda 函数的方法,如:

      plt.scatter(df['a'],df['b'], \
       c = df.index.map(lambda m: 0 if (m.month > 0 and m.month < 7) else 1))
      

      【讨论】:

      猜你喜欢
      • 2021-03-16
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      相关资源
      最近更新 更多