Matplotlib:如何使网格的垂直可选虚线变为虚线? [英] Matplotlib: How to make alternative vertical lines of grid dashed?

查看:36
本文介绍了Matplotlib:如何使网格的垂直可选虚线变为虚线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I had simple integer x-axis, I could use plt.axvline(value) to get vertical lines, but I am wondering how to get vertical dashed lines when we have string x-axis labels.

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()

必填

  • 网格图中的所有其他垂直线都将变为虚线和彩色.
  • 推荐答案

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

    plt.xticks() returns the x tick locations and labels, so we can access the locations by indexing with [0]. It turns out this is just a list of consecutive integer values, so we can loop through them and draw the grid lines manually, with a different style for every other one. With plt.grid(True, axis='y') we make sure the automatic grid is drawn only for the y axis, so that this does not interfere with our custom vertical lines.

    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)
    

    这篇关于Matplotlib:如何使网格的垂直可选虚线变为虚线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆