以日期或其他类型值的特定交替间隔在绘图上设置背景颜色 [英] Set the background color on a plot in specific alternate intervals of dates or other types of values

查看:49
本文介绍了以日期或其他类型值的特定交替间隔在绘图上设置背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个类似于

使用此代码:

  n = 1000xs = np.random.randn(n).cumsum()plt.plot(xs)plt.autoscale(enable=True,axis='both',tight=True)对于范围内的 i (0, len(y_series), 400):plt.axvspan(i, i+100, facecolor='grey', alpha=0.5)

但是,此代码的问题在于我们使用数据输入作为确定灰色区域的参考.相反,我希望灰色区域由与输入分离的x轴或y轴上的可见刻度确定.我不想使用定位器功能,因为这也违背了根据可见刻度值自动"使背景变灰的目的.此外,我们在 x 轴上使用了整数,但理想情况下,这应该适用于日期、浮点数等.

以下是使用日期的示例,其中没有灰色区域:

使用此代码制作且没有自动缩放:

n = 700x_series = pd.date_range(start ='2017-01-01',period = n,freq ='D')y_series = np.random.randn(n).cumsum()无花果,ax = plt.subplots()ax.plot(x_series,y_series)plt.gcf().autofmt_xdate()

PS:我尝试阅读棒列表,但如果关闭自动缩放,该列表无法准确反映可见值.

locs, labels = plt.xticks()打印(位置)

<块引用>

[-200.0. 200. 400. 600. 800. 1000. 1200.]

解决方案

由于注释似乎太复杂而无法解释所有内容,因此这里有一些示例代码,包括 subplots autoscale autofmt_xdate 并重置 xlims.

autoscale 移动xlim,因此应在 alt_bands 获取并重置这些xlim之前调用它.

当处理子图时,大多数函数应该是轴版本而不是 plt 版本.因此,用 ax.get_ticks()代替 plt.ticks() ax.axvspan 代替 plt.axvspan .autofmt_xdate 更改完整图形(旋转并重新对齐 x 轴上的日期,并删除 x 轴上的日期,底部绘图除外).在创建绘图后(在 ax.plot 之后)以及可能更改刻度位置的操作之后,应调用 fig.autofmt_xdate().

 将numpy导入为np将熊猫作为pd导入从 matplotlib 导入 pyplot 作为 pltdef alt_bands(ax=None):ax = ax 或 plt.gca()x_left,x_right = ax.get_xlim()locs = ax.get_xticks()对于 zip(locs[::2], np.concatenate((locs, [x_right]))[1::2]) 中的 loc1, loc2:ax.axvspan(loc1, loc2, facecolor='black', alpha=0.2)ax.set_xlim(x_left, x_right)n = 700x_series = pd.date_range(start='2017-01-01', period=n, freq='D')y_series = np.random.normal(.01, 1, n).cumsum()无花果,轴= plt.subplots(ncols = 2)axes [0] .plot(x_series,y_series)axes [0] .autoscale(enable = True,axis ='both',tight = True)alt_bands(轴[0])axes [1] .plot(x_series [200:400],y_series [200:400])轴[1].自动缩放(启用=真,轴=两者",紧=真)alt_bands(轴[1])fig.autofmt_xdate()plt.show()

I want to do a plot similar to yahoo finance charts where the background color is greyed out in alternate intervals according to the axis ticks date marks. Following an answer from a similar problem I get an image like this:

Using this code:

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)

However, the issue with this code is that we use the data input as a reference for determining the greyed out area. Instead, I want the greyed out area to be determined by the visible ticks on the x-axis or y-axis, decoupled from the input. I do not want to have to use the locator functions, because this also defeated the purpose of 'automatically' greying out the background according to the visible ticks values. Additionally, we used integers in the x-axis, but ideally, this should work for dates, floats, and others.

Here is an example using dates, without the greyed out areas:

Produced with this code and without autoscale:

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: I tried reading the sticks list, but that list does not reflect exactly the visible values if autoscale if turned off.

locs, labels = plt.xticks()
print(locs)

[-200. 0. 200. 400. 600. 800. 1000. 1200.]

解决方案

As the comments seem to be too complicated to explain everything, here is some example code, including subplots, autoscale, autofmt_xdate and resetting the xlims.

autoscale moves the xlims, so it should be called before alt_bands gets and resets these xlims.

When working with subplots, most functions should be the axes version instead of the plt versions. So, ax.get_ticks() instead of plt.ticks() and ax.axvspan instead of plt.axvspan. autofmt_xdate changes the complete figure (rotates and realigns the dates on x-axes, and removes dates on x-axes except the ones of the plots at the bottom). fig.autofmt_xdate() should be called after creating the plot (after ax.plot) and after operations that might change tick positions.

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

def alt_bands(ax=None):
    ax = ax or plt.gca()
    x_left, x_right = ax.get_xlim()
    locs = ax.get_xticks()
    for loc1, loc2 in zip(locs[::2], np.concatenate((locs, [x_right]))[1::2]):
        ax.axvspan(loc1, loc2, facecolor='black', alpha=0.2)
    ax.set_xlim(x_left, x_right)

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

fig, axes = plt.subplots(ncols=2)
axes[0].plot(x_series, y_series)
axes[0].autoscale(enable=True, axis='both', tight=True)
alt_bands(axes[0])

axes[1].plot(x_series[200:400], y_series[200:400])
axes[1].autoscale(enable=True, axis='both', tight=True)
alt_bands(axes[1])

fig.autofmt_xdate()
plt.show()

这篇关于以日期或其他类型值的特定交替间隔在绘图上设置背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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