【问题标题】:Matplotlib: How to make alternative vertical lines of grid dashed?Matplotlib:如何使网格的替代垂直线虚线?
【发布时间】:2020-07-17 22:05:44
【问题描述】:

如果我有简单的整数 x 轴,我可以使用 plt.axvline(value) 来获得垂直 线,但我想知道当我们有字符串 x 轴标签时如何获得垂直虚线。

设置

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline


np.random.seed(123)

x = np.random.normal(0,1,100)
xx = pd.cut(x,20).to_numpy().astype(str)

yy = np.random.normal(0,1,100)

plt.plot(xx,yy,'o')
plt.xticks(rotation=90)
plt.grid(True)

plt.show()

必填

  • 网格图中每隔一条垂直线用虚线着色。

电流输出

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    plt.xticks() 返回 x 刻度位置和标签,因此我们可以通过使用[0] 进行索引来访问这些位置。事实证明,这只是一个连续整数值的列表,因此我们可以循环遍历它们并手动绘制网格线,每个其他的样式都不同。使用plt.grid(True, axis='y'),我们确保仅为 y 轴绘制自动网格,这样就不会干扰我们自定义的垂直线。

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    %matplotlib inline
    
    
    np.random.seed(123)
    
    x = np.random.normal(0,1,100)
    xx = pd.cut(x,20).to_numpy().astype(str)
    
    yy = np.random.normal(0,1,100)
    
    plt.plot(xx,yy,'o')
    plt.xticks(rotation=90)
    
    ############################
    # new code below           #
    ############################
    
    plt.grid(True, axis='y')
    
    for tick in plt.xticks()[0]:
        if tick % 2 == 0:
            plt.axvline(tick, color='gray', linestyle='-', linewidth=1, alpha=.5)
        else:
            plt.axvline(tick, color='red', linestyle='--', linewidth=1, alpha=1)
    

    【讨论】:

      【解决方案2】:

      自己绘制网格线,更改其他垂直线的样式。

      import numpy as np
      import pandas as pd
      import matplotlib.pyplot as plt
      
      np.random.seed(123)
      
      x = np.random.normal(0,1,100)
      xx = pd.cut(x,20).astype(str)
      yy = np.random.normal(0,1,100)
      
      fig = plt.figure()
      ax = fig.add_subplot(111)
      ax.plot(xx, yy,'o')
      plt.xticks(rotation=90)
      
      for index, xmaj in enumerate(ax.xaxis.get_majorticklocs()):
          if index % 2 == 0:
              ax.axvline(x=xmaj, ls='-', linewidth = 1.0, color = 'grey')
          else:
              ## add line change style/color here
              ax.axvline(x=xmaj, ls='--', linewidth = 1.0, color = 'blue')
      for ymaj in ax.yaxis.get_majorticklocs():
          ax.axhline(y=ymaj, ls='-', linewidth = 1.0, color = 'grey')
      
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 2013-04-11
        • 2019-11-04
        • 1970-01-01
        • 2017-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多