Python 在特定的日期间隔或其他类型的值中设置绘图的背景色

Python 在特定的日期间隔或其他类型的值中设置绘图的背景色,python,matplotlib,Python,Matplotlib,我想做一个类似于根据轴刻度日期标记以交替间隔灰显背景色的绘图。下面我得到了这样一张图片: 使用此代码: n = 1000 xs = np.random.randn(n).cumsum() plt.plot(xs) plt.autoscale(enable=True, axis='both', tight=True) for i in range(0, len(y_series), 400): plt.axvspan(i, i+100, facecolor='grey', alpha=0

我想做一个类似于根据轴刻度日期标记以交替间隔灰显背景色的绘图。下面我得到了这样一张图片:

使用此代码:

n = 1000
xs = np.random.randn(n).cumsum()

plt.plot(xs)
plt.autoscale(enable=True, axis='both', tight=True)

for i in range(0, len(y_series), 400):
  plt.axvspan(i, i+100, facecolor='grey', alpha=0.5)
然而,该代码的问题是,我们使用数据输入作为确定灰显区域的参考。相反,我希望灰显区域由x轴或y轴上的可见标记确定,与输入分离。我不想使用定位器功能,因为这也破坏了根据可见刻度值“自动”灰显背景的目的。此外,我们在x轴上使用整数,但理想情况下,这应该适用于日期、浮点等

下面是一个使用日期的示例,没有灰显区域:

使用此代码生成但不自动缩放:

n = 700
x_series = pd.date_range(start='2017-01-01', periods=n, freq='D')
y_series = np.random.randn(n).cumsum()

fig, ax = plt.subplots()
ax.plot(x_series, y_series)
plt.gcf().autofmt_xdate()
PS:我试着阅读棍棒列表,但如果关闭自动缩放,该列表不能准确反映可见值

locs, labels = plt.xticks()
print(locs)
[-200.0.200.400.600.800.1000.1200]


检查代码是否可以帮助您

此处
轴([0.01,0.01,0.98,0.90],facecolor=“white”,frameon=True)
facecolor
中,您可以更改背景,也可以使用十六进制格式的
'#f0'
灰色

from matplotlib.pyplot import *
import subprocess
import sys
import re

# Selection of features following "Writing mathematical expressions" tutorial
mathtext_titles = {
    0: "Header demo",
    1: "Subscripts and superscripts",
    2: "Fractions, binomials and stacked numbers",
    3: "Radicals",
    4: "Fonts",
    5: "Accents",
    6: "Greek, Hebrew",
    7: "Delimiters, functions and Symbols"}
n_lines = len(mathtext_titles)

# Randomly picked examples
mathext_demos = {
    0: r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = "
       r"U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} "
       r"\int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ "
       r"U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_"
       r"{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$",

    1: r"$\alpha_i > \beta_i,\ "
       r"\alpha_{i+1}^j = {\rm sin}(2\pi f_j t_i) e^{-5 t_i/\tau},\ "
       r"\ldots$",

    2: r"$\frac{3}{4},\ \binom{3}{4},\ \genfrac{}{}{0}{}{3}{4},\ "
       r"\left(\frac{5 - \frac{1}{x}}{4}\right),\ \ldots$",

    3: r"$\sqrt{2},\ \sqrt[3]{x},\ \ldots$",

    4: r"$\mathrm{Roman}\ , \ \mathit{Italic}\ , \ \mathtt{Typewriter} \ "
       r"\mathrm{or}\ \mathcal{CALLIGRAPHY}$",

    5: r"$\acute a,\ \bar a,\ \breve a,\ \dot a,\ \ddot a, \ \grave a, \ "
       r"\hat a,\ \tilde a,\ \vec a,\ \widehat{xyz},\ \widetilde{xyz},\ "
       r"\ldots$",

    6: r"$\alpha,\ \beta,\ \chi,\ \delta,\ \lambda,\ \mu,\ "
       r"\Delta,\ \Gamma,\ \Omega,\ \Phi,\ \Pi,\ \Upsilon,\ \nabla,\ "
       r"\aleph,\ \beth,\ \daleth,\ \gimel,\ \ldots$",

    7: r"$\coprod,\ \int,\ \oint,\ \prod,\ \sum,\ "
       r"\log,\ \sin,\ \approx,\ \oplus,\ \star,\ \varpropto,\ "
       r"\infty,\ \partial,\ \Re,\ \leftrightsquigarrow, \ \ldots$"}


def doall():
    # Colors used in mpl online documentation.
    mpl_blue_rvb = (191. / 255., 209. / 256., 212. / 255.)
    mpl_orange_rvb = (202. / 255., 121. / 256., 0. / 255.)
    mpl_grey_rvb = (51. / 255., 51. / 255., 51. / 255.)

    # Creating figure and axis.
    figure(figsize=(6, 7))
    axes([0.01, 0.01, 0.98, 0.90], facecolor="white", frameon=True)
    gca().set_xlim(0., 1.)
    gca().set_ylim(0., 1.)
    gca().set_title("Matplotlib's math rendering engine",
                    color=mpl_grey_rvb, fontsize=14, weight='bold')
    gca().set_xticklabels("", visible=False)
    gca().set_yticklabels("", visible=False)

    # Gap between lines in axes coords
    line_axesfrac = (1. / n_lines)

    # Plotting header demonstration formula
    full_demo = mathext_demos[0]
    annotate(full_demo,
             xy=(0.5, 1. - 0.59 * line_axesfrac),
             color=mpl_orange_rvb, ha='center', fontsize=20)

    # Plotting features demonstration formulae
    for i_line in range(1, n_lines):
        baseline = 1 - i_line * line_axesfrac
        baseline_next = baseline - line_axesfrac
        toptitle = mathtext_titles[i_line] + ":"
        fill_color = ['white', mpl_blue_rvb][i_line % 2]
        fill_between([0., 1.], [baseline, baseline],
                     [baseline_next, baseline_next],
                     color=fill_color, alpha=0.5)
        annotate(toptitle,
                 xy=(0.07, baseline - 0.3 * line_axesfrac),
                 color=mpl_grey_rvb, weight='bold')
        demo = mathext_demos[i_line]
        annotate(demo,
                 xy=(0.05, baseline - 0.75 * line_axesfrac),
                 color=mpl_grey_rvb, fontsize=16)

    for i1 in range(n_lines):
        s1 = mathext_demos[i1]
        print(i1, s1)
    show()


if __name__ == '__main__':
    if '--latex' in sys.argv:
        # Run: python mathtext_examples.py --latex
        # Need amsmath and amssymb packages.
        fd = open("mathtext_examples.ltx", "w")
        fd.write("\\documentclass{article}\n")
        fd.write("\\usepackage{amsmath, amssymb}\n")
        fd.write("\\begin{document}\n")
        fd.write("\\begin{enumerate}\n")

        for i in range(n_lines):
            s = mathext_demos[i]
            s = re.sub(r"(?<!\\)\$", "$$", s)
            fd.write("\\item %s\n" % s)

        fd.write("\\end{enumerate}\n")
        fd.write("\\end{document}\n")
        fd.close()

        subprocess.call(["pdflatex", "mathtext_examples.ltx"])
    else:
        doall()
从matplotlib.pyplot导入*
导入子流程
导入系统
进口稀土
#“编写数学表达式”教程之后的功能选择
mathtext_标题={
0:“标题演示”,
1:“下标和上标”,
2:“分数、二项式和堆叠数字”,
3:“部首”,
4:“字体”,
5:“口音”,
6:“希腊语、希伯来语”,
7:“分隔符、函数和符号”}
n_行=len(数学文本标题)
#随机挑选的例子
mathext_演示={
0:r“$W^{3\beta}{\delta_1\rho_1\sigma_2}=”
r“U^{3\beta}{\delta\u1\rho\u1}+\frac{1}{8\pi2}”
r“\int^{\alpha_2}{\alpha_2}d\alpha^\prime_2\left[\frac{”
r“U^{2\beta}{\delta_1\rho_1}-\alpha^\prime_2U^{1\beta}”
r“{\rho_1\sigma_2}}{U^{0\beta}{\rho_1\sigma_2}}}\right]$”,
1:r“$\alpha\u i>\beta\u i,\”
r“\alpha{i+1}^j={\rm sin}(2\pi f_j t_i)e^{-5 t_i/\tau},\”
r“\ldots$”,
2:r“$\frac{3}{4},\\binom{3}{4},\\genfrac{0}{3}{4},\”
r“\left(\frac{5-\frac{1}{x}}{4}\right),\\ldots$”,
3:r“$\sqrt{2},\\sqrt[3]{x},\\ldots$”,
4:r“$\mathrm{Roman}\,\\mathit{Italic}\,\\mathtt{Typewriter}\”
r“\mathrm{或}\\mathcal{书法}$”,
5:r“$\acute a、\\bar a、\\breve a、\\dot a、\\ddot a、\\grave a、\”
r“\hat a,\\tilde a,\\vec a,\\widehat{xyz},\\widetilde{xyz},\”
r“\ldots$”,
6:r“$\alpha,\\beta,\\chi,\\delta,\\lambda,\\mu,\”
r“\Delta、\\Gamma、\\Omega、\\Phi、\\Pi、\\Upsilon、\\nabla、\”
r“\aleph,\\beth,\\daleth,\\gimel,\\ldots$”,
7:r“$\coprod,\\int,\\point,\\prod,\\sum,\”
r“\log,\\sin,\\approx,\\oplus,\\star,\\varpropto,\”
r“\infty,\\partial,\\Re,\\leftrightsquigarrow,\\ldots$”}
def doall():
#mpl在线文档中使用的颜色。
mpl_blue_rvb=(191./255,209./256,212./255.)
mpl_orange_rvb=(202./255.,121./256.,0./255.)
mpl_grey_rvb=(51./255,51./255,51./255.)
#创建图形和轴。
图(figsize=(6,7))
轴([0.01,0.01,0.98,0.90],facecolor=“白色”,frameon=True)
gca().set_xlim(0,1.)
gca().set_ylim(0,1.)
gca().set_title(“Matplotlib的数学渲染引擎”,
颜色=mpl_灰色_rvb,字体大小=14,重量='bold')
gca().setxticklabels(“”,visible=False)
gca().set_yticklabels(“”,visible=False)
#轴线坐标中的线间距
行_axesfrac=(1./n_行)
#标绘表头演示公式
完整演示=数学文本演示[0]
注释(完整演示,
xy=(0.5,1-0.59*line_axesfrac),
颜色=mpl_橙色_rvb,ha='center',fontsize=20)
#绘图特征演示公式
对于范围内的i_线(1,n_线):
基线=1-i_线*线轴断裂
基线\u下一步=基线-线\u axesfrac
toptitle=mathtext\u标题[i\u行]+“:”
填充颜色=[“白色”,mpl_蓝色][i_行%2]
填充([0,1.],[baseline,baseline],
[基线下一步,基线下一步],
颜色=填充颜色,α=0.5)
注释(标题,
xy=(0.07,基线-0.3*line_axesfrac),
颜色=mpl\U灰色\U rvb,重量='bold')
demo=mathext\u demos[i\u行]
注释(演示),
xy=(0.05,基线-0.75*line_axesfrac),
颜色=mpl_灰色_rvb,字体大小=16)
对于范围内的i1(n_行):
s1=数学文本演示[i1]
打印(i1,s1)
show()
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
如果sys.argv中有“-latex”:
#运行:python mathtext_examples.py--latex
#需要amsmath和amssymb软件包。
fd=打开(“mathtext_examples.ltx”,“w”)
fd.write(\\documentclass{article}\n)
fd.write(\\usepackage{amsmath,amssymb}\n)
fd.write(\\begin{document}\n)
fd.write(\\begin{enumerate}\n)
对于范围内的i(n_行):
s=数学文本演示[i]

s=re.sub(r)(?我认为这个问题有点棘手,要确保涵盖所有情况很麻烦。
xticks
有时会在
xlim
的左右两侧返回值,但这只是开始。如果数据超出最右边的xtick,或者在最左边的
xtick
之前开始,等等,会发生什么?

例如,在下面的许多情况下,我希望在
xmin
xmax
处开始(或停止)标注栏,因为如果我不这样做,并且索引会在标记开始(或停止)后跳过标注栏,则会有一个长的未完成的部分
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(100, 11000, 7500)
y = x * np.sin(0.001*x) ** 2

def alt_bands(x):
    locs, labels = plt.xticks()
    x_left, x_right = plt.xlim()
    for i, loc in enumerate(locs):
        if i%2 == 1 and i<len(locs)-1 and loc<x[-1] and (loc>x_left or x[0]>x_left):
            L = max(x_left, x[0], loc)
            R = min(x_right, x[-1], locs[i+1])
            if x[0] <= L and R>L:
                plt.axvspan(L, R, facecolor='grey', alpha=0.5)

plt.plot(x, y)
alt_bands()