Matplotlib:如何使网格的垂直垂直线变为虚线?

时间:2020-04-05 23:24:51

标签: python matplotlib

如果我有简单的整数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()

必需

  • 网格图中的所有其他垂直线都将变为虚线和彩色。

当前输出

enter image description here

2 个答案:

答案 0 :(得分: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)

Custom Grid

答案 1 :(得分:1)

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

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

alternating gridlines image

相关问题