Files
anders 16c54c6653 Tilføjet venv med docling og afhængigheder
Testfiler opdelt i PNG og previews
2026-10-27 12:20:23 +01:00

2309 lines
89 KiB
Python

"""Test cases for time series specific (freq conversion, etc)"""
from datetime import (
date,
datetime,
time,
timedelta,
)
import pickle
import numpy as np
import pytest
from pandas._libs.tslibs import (
BaseOffset,
to_offset,
)
from pandas.core.dtypes.dtypes import PeriodDtype
import pandas as pd
import pandas._testing as tm
from pandas.core.indexes.datetimes import (
DatetimeIndex,
bdate_range,
date_range,
)
from pandas.core.indexes.period import (
Period,
PeriodIndex,
period_range,
)
from pandas.core.indexes.timedeltas import timedelta_range
from pandas.tests.plotting.common import _check_ticks_props
from pandas.tseries.offsets import WeekOfMonth
mpl = pytest.importorskip("matplotlib")
plt = pytest.importorskip("matplotlib.pyplot")
import pandas.plotting._matplotlib.converter as conv
class TestTSPlot:
def test_ts_plot_with_tz(self, tz_aware_fixture):
# GH2877, GH17173, GH31205, GH31580
tz = tz_aware_fixture
index = date_range("1/1/2011", periods=2, freq="h", tz=tz)
ts = pd.Series([188.5, 328.25], index=index)
_check_plot_works(ts.plot)
ax = ts.plot()
xdata = next(iter(ax.get_lines())).get_xdata()
# xdata are raw Period ordinals (int64); reconstruct to check labels
first = Period(ordinal=int(xdata[0]), freq=ax.freq)
last = Period(ordinal=int(xdata[-1]), freq=ax.freq)
assert (first.hour, first.minute) == (0, 0)
assert (last.hour, last.minute) == (1, 0)
def test_ts_plot_tz_aware_values(self):
# GH#64613 the ts path read Series.values, which both raised the
# lossy-.values deprecation from inside pandas and plotted tz-aware
# values one utc offset away from where the non-ts path puts them
values = date_range("2020-01-01", periods=10, tz="US/Pacific")
_, (ax1, ax2) = mpl.pyplot.subplots(2)
with tm.assert_produces_warning(None):
pd.Series(values, index=date_range("2021-01-01", periods=10)).plot(ax=ax1)
pd.Series(values).plot(ax=ax2)
tm.assert_numpy_array_equal(ax1.get_yticks(), ax2.get_yticks())
def test_replot_tz_aware_values(self):
# GH#64613 replotting onto an axes that already holds a coarser-freq
# series goes through _replot_ax, which dropped the timezone
values = date_range("2020-01-01", periods=3, tz="US/Pacific")
_, ax = mpl.pyplot.subplots()
with tm.assert_produces_warning(None):
ser = pd.Series(
values, index=date_range("2020-01-31", periods=3, freq="ME")
)
ser.plot(ax=ax)
other = pd.Series(np.arange(6.0), index=date_range("2020-01-01", periods=6))
other.plot(ax=ax)
ydata = ax.get_lines()[0].get_ydata()
tm.assert_numpy_array_equal(ydata, np.asarray(values))
def test_fontsize_set_correctly(self):
# For issue #8765
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((10, 9)), index=range(10)
)
_, ax = mpl.pyplot.subplots()
df.plot(fontsize=2, ax=ax)
for label in ax.get_xticklabels() + ax.get_yticklabels():
assert label.get_fontsize() == 2
def test_frame_inferred(self):
# inferred freq
idx = date_range("1/1/1987", freq="MS", periods=10)
idx = DatetimeIndex(idx.values, freq=None)
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((len(idx), 3)), index=idx
)
_check_plot_works(df.plot)
# axes freq
idx = idx[0:4].union(idx[6:])
df2 = pd.DataFrame(
np.random.default_rng(2).standard_normal((len(idx), 3)), index=idx
)
_check_plot_works(df2.plot)
def test_frame_inferred_n_gt_1(self):
# N > 1
idx = date_range("2008-1-1 00:15:00", freq="15min", periods=10)
idx = DatetimeIndex(idx.values, freq=None)
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((len(idx), 3)), index=idx
)
_check_plot_works(df.plot)
def test_is_error_nozeroindex(self):
# GH11858
i = np.array([1, 2, 3])
a = pd.DataFrame(i, index=i)
_check_plot_works(a.plot, xerr=a)
_check_plot_works(a.plot, yerr=a)
def test_nonnumeric_exclude(self):
idx = date_range("1/1/1987", freq="YE", periods=3)
df = pd.DataFrame({"A": ["x", "y", "z"], "B": [1, 2, 3]}, idx)
fig, ax = mpl.pyplot.subplots()
df.plot(ax=ax) # it works
assert len(ax.get_lines()) == 1 # B was plotted
def test_nonnumeric_exclude_error(self):
idx = date_range("1/1/1987", freq="YE", periods=3)
df = pd.DataFrame({"A": ["x", "y", "z"], "B": [1, 2, 3]}, idx)
msg = "no numeric data to plot"
with pytest.raises(TypeError, match=msg):
df["A"].plot()
@pytest.mark.parametrize("freq", ["s", "min", "h", "D", "W", "M", "Q", "Y"])
def test_tsplot_period(self, freq):
idx = period_range("12/31/1999", freq=freq, periods=10)
ser = pd.Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
_, ax = mpl.pyplot.subplots()
_check_plot_works(ser.plot, ax=ax)
@pytest.mark.parametrize(
"freq", ["s", "min", "h", "D", "W", "ME", "QE-DEC", "YE", "1B30Min"]
)
def test_tsplot_datetime(self, freq):
idx = date_range("12/31/1999", freq=freq, periods=10)
ser = pd.Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
_, ax = mpl.pyplot.subplots()
_check_plot_works(ser.plot, ax=ax)
def test_tsplot(self):
ts = pd.Series(
np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
)
_, ax = mpl.pyplot.subplots()
ts.plot(style="k", ax=ax)
color = (0.0, 0.0, 0.0, 1)
assert color == ax.get_lines()[0].get_color()
@pytest.mark.parametrize("index", [None, date_range("2020-01-01", periods=10)])
def test_both_style_and_color(self, index):
ts = pd.Series(np.arange(10, dtype=np.float64), index=index)
msg = (
"Cannot pass 'style' string with a color symbol and 'color' "
"keyword argument. Please use one or the other or pass 'style' "
"without a color symbol"
)
with pytest.raises(ValueError, match=msg):
ts.plot(style="b-", color="#000099")
@pytest.mark.parametrize("freq", ["ms", "us"])
def test_high_freq(self, freq):
_, ax = mpl.pyplot.subplots()
rng = date_range("1/1/2012", periods=10, freq=freq)
ser = pd.Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
_check_plot_works(ser.plot, ax=ax)
def test_get_datevalue(self):
assert conv._get_datevalue(None, "D") is None
assert conv._get_datevalue(1987, "Y") == 1987
assert (
conv._get_datevalue(Period("1987", "Y"), "M")
== Period("1987-12", "M").ordinal
)
assert conv._get_datevalue("1/1/1987", "D") == Period("1987-1-1", "D").ordinal
@pytest.mark.parametrize(
"freq, expected_string",
[["YE-DEC", "t = 2014 y = 1.000000"], ["D", "t = 2014-01-01 y = 1.000000"]],
)
def test_ts_plot_format_coord(self, freq, expected_string):
ser = pd.Series(1, index=date_range("2014-01-01", periods=3, freq=freq))
_, ax = mpl.pyplot.subplots()
ser.plot(ax=ax)
first_line = ax.get_lines()[0]
first_x = int(first_line.get_xdata()[0])
first_y = first_line.get_ydata()[0]
assert expected_string == ax.format_coord(first_x, first_y)
def test_ts_plot_format_coord_bday(self):
# format_coord is the hover-tooltip; verify it formats BDay correctly
# without creating deprecated Period[B].
ser = pd.Series(1, index=date_range("2014-01-01", periods=3, freq="B"))
_, ax = mpl.pyplot.subplots()
ser.plot(ax=ax)
first_line = ax.get_lines()[0]
# int64 bday ordinal, not deprecated Period[B]
first_x = first_line.get_xdata()[0]
first_y = first_line.get_ydata()[0]
assert ax.format_coord(first_x, first_y) == "t = 2014-01-01 y = 1.000000"
def test_bday_set_xlim_with_strings_or_datetimes(self):
# GH#64244 - After a BDay plot, ax.set_xlim() with string or datetime
# arguments should convert them to business-day ordinals via
# PeriodConverter (which is now explicitly stored on the axis).
idx = date_range("2020-01-01", periods=20, freq="B")
ser = pd.Series(range(20), index=idx)
_, ax = mpl.pyplot.subplots()
ser.plot(ax=ax)
# string arguments
ax.set_xlim("2020-01-06", "2020-01-10") # Mon, Fri of week 2
left, right = ax.get_xlim()
assert int(left) == conv.bday_count("2020-01-06")
assert int(right) == conv.bday_count("2020-01-10")
# datetime arguments
ax.set_xlim(datetime(2020, 1, 12), datetime(2020, 1, 16))
left, right = ax.get_xlim()
assert int(left) == conv.bday_count("2020-01-12")
assert int(right) == conv.bday_count("2020-01-16")
@pytest.mark.parametrize("freq", ["s", "min", "h", "D", "W", "M", "Q", "Y"])
def test_line_plot_period_series(self, freq):
idx = period_range("12/31/1999", freq=freq, periods=10)
ser = pd.Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
_check_plot_works(ser.plot, ser.index.freq)
@pytest.mark.parametrize(
"frqncy", ["1s", "3s", "5min", "7h", "4D", "8W", "11M", "3Y"]
)
def test_line_plot_period_mlt_series(self, frqncy):
# test period index line plot for series with multiples (`mlt`) of the
# frequency (`frqncy`) rule code. tests resolution of issue #14763
idx = period_range("12/31/1999", freq=frqncy, periods=10)
s = pd.Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
_check_plot_works(s.plot, s.index.freq)
@pytest.mark.parametrize(
"freq", ["s", "min", "h", "D", "W", "ME", "QE-DEC", "YE", "1B30Min"]
)
def test_line_plot_datetime_series(self, freq):
idx = date_range("12/31/1999", freq=freq, periods=10)
ser = pd.Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
_check_plot_works(ser.plot, ser.index.freq.rule_code)
@pytest.mark.parametrize("freq", ["s", "min", "h", "D", "W", "ME", "QE", "YE"])
def test_line_plot_period_frame(self, freq):
idx = date_range("12/31/1999", freq=freq, periods=10)
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((len(idx), 3)),
index=idx,
columns=["A", "B", "C"],
)
_check_plot_works(df.plot, df.index.freq)
@pytest.mark.parametrize(
"frqncy", ["1s", "3s", "5min", "7h", "4D", "8W", "11M", "3Y"]
)
def test_line_plot_period_mlt_frame(self, frqncy):
# test period index line plot for DataFrames with multiples (`mlt`)
# of the frequency (`frqncy`) rule code. tests resolution of issue
# #14763
idx = period_range("12/31/1999", freq=frqncy, periods=10)
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((len(idx), 3)),
index=idx,
columns=["A", "B", "C"],
)
freq = df.index.freq
_check_plot_works(df.plot, freq)
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
@pytest.mark.parametrize(
"freq", ["s", "min", "h", "D", "W", "ME", "QE-DEC", "YE", "1B30Min"]
)
def test_line_plot_datetime_frame(self, freq):
idx = date_range("12/31/1999", freq=freq, periods=10)
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((len(idx), 3)),
index=idx,
columns=["A", "B", "C"],
)
freq = PeriodDtype(df.index.freq)._freqstr
freq = df.index.to_period(freq).freq
_check_plot_works(df.plot, freq)
@pytest.mark.parametrize(
"freq", ["s", "min", "h", "D", "W", "ME", "QE-DEC", "YE", "1B30Min"]
)
def test_line_plot_inferred_freq(self, freq):
idx = date_range("12/31/1999", freq=freq, periods=10)
ser = pd.Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
ser = pd.Series(ser.values, pd.Index(np.asarray(ser.index)))
inferred = ser.index._data._inferred_freq_str
_check_plot_works(ser.plot, inferred)
ser = ser.iloc[[0, 3, 5, 6]]
_check_plot_works(ser.plot)
def test_line_plot_descending_datetime_index(self):
# GH#64819 - descending DatetimeIndex (negative inferred freq) should plot
idx = date_range("2020-01-03", periods=3, freq="-1D")
df = pd.DataFrame([0.5, 1, 2], index=idx)
_check_plot_works(df.plot)
def test_fake_inferred_business(self):
_, ax = mpl.pyplot.subplots()
rng = date_range("2001-1-1", "2001-1-10")
ts = pd.Series(range(len(rng)), index=rng)
ts = pd.concat([ts[:3], ts[5:]])
ts.plot(ax=ax)
assert not hasattr(ax, "freq")
def test_plot_offset_freq(self):
ser = pd.Series(
np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
)
_check_plot_works(ser.plot)
def test_plot_offset_freq_business(self):
dr = date_range("2023-01-01", freq="BQS", periods=10)
ser = pd.Series(np.random.default_rng(2).standard_normal(len(dr)), index=dr)
_check_plot_works(ser.plot)
def test_plot_multiple_inferred_freq(self):
dr = pd.Index(
[datetime(2000, 1, 1), datetime(2000, 1, 6), datetime(2000, 1, 11)]
)
ser = pd.Series(np.random.default_rng(2).standard_normal(len(dr)), index=dr)
_check_plot_works(ser.plot)
def test_irreg_hf(self):
idx = date_range("2012-6-22 21:59:51", freq="s", periods=10)
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((len(idx), 2)), index=idx
)
irreg = df.iloc[[0, 1, 3, 4]]
_, ax = mpl.pyplot.subplots()
irreg.plot(ax=ax)
diffs = pd.Series(ax.get_lines()[0].get_xydata()[:, 0]).diff()
sec = 1.0 / 24 / 60 / 60
assert (np.fabs(diffs[1:] - [sec, sec * 2, sec]) < 1e-8).all()
def test_irreg_hf_object(self):
idx = date_range("2012-6-22 21:59:51", freq="s", periods=10)
df2 = pd.DataFrame(
np.random.default_rng(2).standard_normal((len(idx), 2)), index=idx
)
_, ax = mpl.pyplot.subplots()
df2.index = df2.index.astype(object)
df2.plot(ax=ax)
diffs = pd.Series(ax.get_lines()[0].get_xydata()[:, 0]).diff()
sec = 1.0 / 24 / 60 / 60
assert (np.fabs(diffs[1:] - sec) < 1e-8).all()
def test_irregular_datetime64_repr_bug(self):
ser = pd.Series(
np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
)
ser = ser.iloc[[0, 1, 2, 7]]
_, ax = mpl.pyplot.subplots()
ret = ser.plot(ax=ax)
assert ret is not None
for rs, xp in zip(ax.get_lines()[0].get_xdata(), ser.index, strict=True):
assert rs == xp
def test_business_freq(self):
bts = pd.Series(range(5), period_range("2020-01-01", periods=5))
msg = r"PeriodDtype\[B\] is deprecated"
dt = bts.index[0].to_timestamp()
with tm.assert_produces_warning(FutureWarning, match=msg):
bts.index = period_range(start=dt, periods=len(bts), freq="B")
_, ax = mpl.pyplot.subplots()
bts.plot(ax=ax)
# x-data is plain int64 business-day ordinals (not Period[B])
assert ax.get_lines()[0].get_xydata()[0, 0] == bts.index[0].ordinal
idx = ax.get_lines()[0].get_xdata()
# consecutive business days should produce consecutive ordinals
assert np.all(np.diff(idx) == 1)
def test_business_freq_convert(self):
bts = pd.Series(
np.arange(50, dtype=np.float64),
index=date_range("2020-01-01", periods=50, freq="B"),
).asfreq("BME")
ts = bts.to_period("M")
_, ax = mpl.pyplot.subplots()
bts.plot(ax=ax)
assert ax.get_lines()[0].get_xydata()[0, 0] == ts.index[0].ordinal
idx = ax.get_lines()[0].get_xdata()
assert PeriodIndex.from_ordinals(idx, freq=ax.freq).freqstr == "M"
def test_business_freq_no_weekend_gaps(self):
# Verify that plotting a BDay-frequency series produces evenly-spaced
# x-coordinates with no gaps at weekends. The implementation converts
# DatetimeIndex to int64 business-day ordinals (via np.busday_count),
# so Fri->Mon is a 1-unit step rather than the 3-unit date2num gap.
# See GH#1482.
idx = date_range("2020-01-01", periods=30, freq="B")
ser = pd.Series(range(len(idx)), index=idx)
_, ax = mpl.pyplot.subplots()
ser.plot(ax=ax)
x_values = ax.get_lines()[0].get_xydata()[:, 0]
diffs = np.unique(np.diff(x_values))
# All consecutive x-coordinates should be uniformly spaced (no 3-unit
# weekend gaps that would appear if raw date2num floats were used).
assert len(diffs) == 1, f"Expected uniform spacing, got distinct diffs: {diffs}"
def test_freq_with_no_period_alias(self):
# GH34487
freq = WeekOfMonth()
bts = pd.Series(
np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
).asfreq(freq)
_, ax = mpl.pyplot.subplots()
bts.plot(ax=ax)
idx = ax.get_lines()[0].get_xdata()
msg = "freq not specified and cannot be inferred"
with pytest.raises(ValueError, match=msg):
PeriodIndex(data=idx)
def test_nonzero_base(self):
# GH2571
idx = date_range("2012-12-20", periods=24, freq="h") + timedelta(minutes=30)
df = pd.DataFrame(np.arange(24), index=idx)
_, ax = mpl.pyplot.subplots()
df.plot(ax=ax)
rs = ax.get_lines()[0].get_xdata()
assert not pd.Index(rs).is_normalized
def test_dataframe(self):
bts = pd.DataFrame(
{
"a": pd.Series(
np.arange(10, dtype=np.float64),
index=date_range("2020-01-01", periods=10),
)
}
)
_, ax = mpl.pyplot.subplots()
bts.plot(ax=ax)
idx = ax.get_lines()[0].get_xdata()
tm.assert_index_equal(
bts.index.to_period(), PeriodIndex.from_ordinals(idx, freq=ax.freq)
)
@pytest.mark.parametrize(
"obj",
[
pd.Series(
np.arange(10, dtype=np.float64),
index=date_range("2020-01-01", periods=10),
),
pd.DataFrame(
{
"a": pd.Series(
np.arange(10, dtype=np.float64),
index=date_range("2020-01-01", periods=10),
),
"b": pd.Series(
np.arange(10, dtype=np.float64),
index=date_range("2020-01-01", periods=10),
)
+ 1,
}
),
],
)
def test_axis_limits(self, obj):
_, ax = mpl.pyplot.subplots()
obj.plot(ax=ax)
xlim = ax.get_xlim()
ax.set_xlim(xlim[0] - 5, xlim[1] + 10)
result = ax.get_xlim()
assert result[0] == xlim[0] - 5
assert result[1] == xlim[1] + 10
# string
expected = (Period("1/1/2000", ax.freq), Period("4/1/2000", ax.freq))
ax.set_xlim("1/1/2000", "4/1/2000")
result = ax.get_xlim()
assert int(result[0]) == expected[0].ordinal
assert int(result[1]) == expected[1].ordinal
# datetime
expected = (Period("1/1/2000", ax.freq), Period("4/1/2000", ax.freq))
ax.set_xlim(datetime(2000, 1, 1), datetime(2000, 4, 1))
result = ax.get_xlim()
assert int(result[0]) == expected[0].ordinal
assert int(result[1]) == expected[1].ordinal
def test_get_finder(self):
assert conv.get_finder(to_offset("B")) == conv._daily_finder
assert conv.get_finder(to_offset("D")) == conv._daily_finder
assert conv.get_finder(to_offset("ME")) == conv._monthly_finder
assert conv.get_finder(to_offset("QE")) == conv._quarterly_finder
assert conv.get_finder(to_offset("YE")) == conv._annual_finder
assert conv.get_finder(to_offset("W")) == conv._daily_finder
def test_finder_daily(self):
day_lst = [10, 40, 252, 400, 950, 2750, 10000]
# BDay ordinals are now computed via np.busday_count (no deprecated Period[B])
xpl1 = xpl2 = [conv.bday_count(bdate_range("1999-1-1", periods=1)[0])] * len(
day_lst
)
rs1 = []
rs2 = []
for n in day_lst:
rng = bdate_range("1999-1-1", periods=n)
ser = pd.Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
_, ax = mpl.pyplot.subplots()
ser.plot(ax=ax)
xaxis = ax.get_xaxis()
rs1.append(xaxis.get_majorticklocs()[0])
vmin, vmax = ax.get_xlim()
ax.set_xlim(vmin + 0.9, vmax)
rs2.append(xaxis.get_majorticklocs()[0])
mpl.pyplot.close(ax.get_figure())
assert rs1 == xpl1
assert rs2 == xpl2
def test_finder_quarterly(self):
yrs = [3.5, 11]
xpl1 = xpl2 = [Period("1988Q1").ordinal] * len(yrs)
rs1 = []
rs2 = []
for n in yrs:
rng = period_range("1987Q2", periods=int(n * 4), freq="Q")
ser = pd.Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
_, ax = mpl.pyplot.subplots()
ser.plot(ax=ax)
xaxis = ax.get_xaxis()
rs1.append(xaxis.get_majorticklocs()[0])
(vmin, vmax) = ax.get_xlim()
ax.set_xlim(vmin + 0.9, vmax)
rs2.append(xaxis.get_majorticklocs()[0])
mpl.pyplot.close(ax.get_figure())
assert rs1 == xpl1
assert rs2 == xpl2
def test_finder_monthly(self):
yrs = [1.15, 2.5, 4, 11]
xpl1 = xpl2 = [Period("Jan 1988").ordinal] * len(yrs)
rs1 = []
rs2 = []
for n in yrs:
rng = period_range("1987Q2", periods=int(n * 12), freq="M")
ser = pd.Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
_, ax = mpl.pyplot.subplots()
ser.plot(ax=ax)
xaxis = ax.get_xaxis()
rs1.append(xaxis.get_majorticklocs()[0])
vmin, vmax = ax.get_xlim()
ax.set_xlim(vmin + 0.9, vmax)
rs2.append(xaxis.get_majorticklocs()[0])
mpl.pyplot.close(ax.get_figure())
assert rs1 == xpl1
assert rs2 == xpl2
def test_finder_monthly_long(self):
rng = period_range("1988Q1", periods=24 * 12, freq="M")
ser = pd.Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
_, ax = mpl.pyplot.subplots()
ser.plot(ax=ax)
xaxis = ax.get_xaxis()
rs = xaxis.get_majorticklocs()[0]
xp = Period("1989Q1", "M").ordinal
assert rs == xp
def test_finder_annual(self):
xp = [1987, 1988, 1990, 1990, 1995, 2020, 2070, 2170]
xp = [Period(str(x), freq="Y").ordinal for x in xp]
rs = []
for nyears in [5, 10, 19, 49, 99, 199, 599, 1001]:
rng = period_range("1987", periods=nyears, freq="Y")
ser = pd.Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
_, ax = mpl.pyplot.subplots()
ser.plot(ax=ax)
xaxis = ax.get_xaxis()
rs.append(xaxis.get_majorticklocs()[0])
mpl.pyplot.close(ax.get_figure())
assert rs == xp
@pytest.mark.slow
def test_finder_minutely(self):
nminutes = 1 * 24 * 60
rng = date_range("1/1/1999", freq="Min", periods=nminutes)
ser = pd.Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
_, ax = mpl.pyplot.subplots()
ser.plot(ax=ax)
xaxis = ax.get_xaxis()
rs = xaxis.get_majorticklocs()[0]
xp = Period("1/1/1999", freq="Min").ordinal
assert rs == xp
def test_finder_hourly(self):
nhours = 23
rng = date_range("1/1/1999", freq="h", periods=nhours)
ser = pd.Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
_, ax = mpl.pyplot.subplots()
ser.plot(ax=ax)
xaxis = ax.get_xaxis()
rs = xaxis.get_majorticklocs()[0]
xp = Period("1/1/1999", freq="h").ordinal
assert rs == xp
@pytest.mark.parametrize(
"freq, equiv_freq", [("h", "60min"), ("2h", "120min"), ("D", "24h")]
)
def test_finder_period_equivalent_freq_same_labels(self, freq, equiv_freq):
# GH#57587 equivalent frequencies (e.g. "h" and "60min") must render
# identical x-axis tick labels, not just identical line data.
def _tick_labels(frqncy):
idx = period_range("2000-01-01", freq=frqncy, periods=4)
df = pd.DataFrame(np.array([0, 1, 0, 1]), index=idx, columns=["A"])
_, ax = mpl.pyplot.subplots()
df.plot(ax=ax)
ax.figure.canvas.draw()
labels = [
label.get_text()
for label in list(ax.get_xticklabels(minor=False))
+ list(ax.get_xticklabels(minor=True))
if label.get_text()
]
mpl.pyplot.close(ax.figure)
return sorted(labels)
expected = _tick_labels(freq)
# sanity check: more than just the two endpoints are labeled, so a
# regression that collapses the ticks would not silently match
assert len(expected) > 2
assert _tick_labels(equiv_freq) == expected
def test_gaps(self):
ts = pd.Series(
np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
)
ts.iloc[5:7] = np.nan
_, ax = mpl.pyplot.subplots()
ts.plot(ax=ax)
lines = ax.get_lines()
assert len(lines) == 1
line = lines[0]
data = line.get_xydata()
data = np.ma.MaskedArray(data, mask=pd.isna(data), fill_value=np.nan)
assert isinstance(data, np.ma.core.MaskedArray)
mask = data.mask
assert mask[5:7, 1].all()
def test_gaps_irregular(self):
# irregular
ts = pd.Series(
np.arange(30, dtype=np.float64), index=date_range("2020-01-01", periods=30)
)
ts = ts.iloc[[0, 1, 2, 5, 7, 9, 12, 15, 20]]
ts.iloc[2:5] = np.nan
_, ax = mpl.pyplot.subplots()
ax = ts.plot(ax=ax)
lines = ax.get_lines()
assert len(lines) == 1
line = lines[0]
data = line.get_xydata()
data = np.ma.MaskedArray(data, mask=pd.isna(data), fill_value=np.nan)
assert isinstance(data, np.ma.core.MaskedArray)
mask = data.mask
assert mask[2:5, 1].all()
def test_gaps_non_ts(self):
# non-ts
idx = [0, 1, 2, 5, 7, 9, 12, 15, 20]
ser = pd.Series(np.random.default_rng(2).standard_normal(len(idx)), idx)
ser.iloc[2:5] = np.nan
_, ax = mpl.pyplot.subplots()
ser.plot(ax=ax)
lines = ax.get_lines()
assert len(lines) == 1
line = lines[0]
data = line.get_xydata()
data = np.ma.MaskedArray(data, mask=pd.isna(data), fill_value=np.nan)
assert isinstance(data, np.ma.core.MaskedArray)
mask = data.mask
assert mask[2:5, 1].all()
def test_gap_upsample(self):
low = pd.Series(
np.arange(10, dtype=np.float64), index=date_range("2020-01-01", periods=10)
)
low.iloc[5:7] = np.nan
_, ax = mpl.pyplot.subplots()
low.plot(ax=ax)
idxh = date_range(low.index[0], low.index[-1], freq="12h")
s = pd.Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
s.plot(secondary_y=True)
lines = ax.get_lines()
assert len(lines) == 1
assert len(ax.right_ax.get_lines()) == 1
line = lines[0]
data = line.get_xydata()
data = np.ma.MaskedArray(data, mask=pd.isna(data), fill_value=np.nan)
assert isinstance(data, np.ma.core.MaskedArray)
mask = data.mask
assert mask[5:7, 1].all()
def test_secondary_y(self):
ser = pd.Series(np.random.default_rng(2).standard_normal(10))
fig, _ = mpl.pyplot.subplots()
ax = ser.plot(secondary_y=True)
assert hasattr(ax, "left_ax")
assert not hasattr(ax, "right_ax")
axes = fig.get_axes()
line = ax.get_lines()[0]
xp = pd.Series(line.get_ydata(), line.get_xdata())
tm.assert_series_equal(ser, xp)
assert ax.get_yaxis().get_ticks_position() == "right"
assert not axes[0].get_yaxis().get_visible()
def test_secondary_y_yaxis(self):
pd.Series(np.random.default_rng(2).standard_normal(10))
ser2 = pd.Series(np.random.default_rng(2).standard_normal(10))
_, ax2 = mpl.pyplot.subplots()
ser2.plot(ax=ax2)
assert ax2.get_yaxis().get_ticks_position() == "left"
def test_secondary_both(self):
ser = pd.Series(np.random.default_rng(2).standard_normal(10))
ser2 = pd.Series(np.random.default_rng(2).standard_normal(10))
ax = ser2.plot()
ax2 = ser.plot(secondary_y=True)
assert ax.get_yaxis().get_visible()
assert not hasattr(ax, "left_ax")
assert hasattr(ax, "right_ax")
assert hasattr(ax2, "left_ax")
assert not hasattr(ax2, "right_ax")
def test_secondary_y_ts(self):
idx = date_range("1/1/2000", periods=10, unit="ns")
ser = pd.Series(np.random.default_rng(2).standard_normal(10), idx)
fig, _ = mpl.pyplot.subplots()
ax = ser.plot(secondary_y=True)
assert hasattr(ax, "left_ax")
assert not hasattr(ax, "right_ax")
axes = fig.get_axes()
line = ax.get_lines()[0]
idx = PeriodIndex.from_ordinals(line.get_xdata(), freq=ax.freq)
xp = pd.Series(line.get_ydata(), idx).to_timestamp()
xp.index = xp.index.as_unit("ns")
tm.assert_series_equal(ser, xp)
assert ax.get_yaxis().get_ticks_position() == "right"
assert not axes[0].get_yaxis().get_visible()
def test_secondary_y_ts_yaxis(self):
idx = date_range("1/1/2000", periods=10)
ser2 = pd.Series(np.random.default_rng(2).standard_normal(10), idx)
_, ax2 = mpl.pyplot.subplots()
ser2.plot(ax=ax2)
assert ax2.get_yaxis().get_ticks_position() == "left"
def test_secondary_y_ts_visible(self):
idx = date_range("1/1/2000", periods=10)
ser2 = pd.Series(np.random.default_rng(2).standard_normal(10), idx)
ax = ser2.plot()
assert ax.get_yaxis().get_visible()
def test_secondary_kde(self):
pytest.importorskip("scipy")
ser = pd.Series(np.random.default_rng(2).standard_normal(10))
fig, ax = mpl.pyplot.subplots()
ax = ser.plot(secondary_y=True, kind="density", ax=ax)
assert hasattr(ax, "left_ax")
assert not hasattr(ax, "right_ax")
axes = fig.get_axes()
assert axes[1].get_yaxis().get_ticks_position() == "right"
def test_secondary_bar(self):
ser = pd.Series(np.random.default_rng(2).standard_normal(10))
fig, ax = mpl.pyplot.subplots()
ser.plot(secondary_y=True, kind="bar", ax=ax)
axes = fig.get_axes()
assert axes[1].get_yaxis().get_ticks_position() == "right"
def test_secondary_frame(self):
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((5, 3)), columns=["a", "b", "c"]
)
axes = df.plot(secondary_y=["a", "c"], subplots=True)
assert axes[0].get_yaxis().get_ticks_position() == "right"
assert axes[1].get_yaxis().get_ticks_position() == "left"
assert axes[2].get_yaxis().get_ticks_position() == "right"
def test_secondary_bar_frame(self):
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((5, 3)), columns=["a", "b", "c"]
)
axes = df.plot(kind="bar", secondary_y=["a", "c"], subplots=True)
assert axes[0].get_yaxis().get_ticks_position() == "right"
assert axes[1].get_yaxis().get_ticks_position() == "left"
assert axes[2].get_yaxis().get_ticks_position() == "right"
def test_mixed_freq_regular_first(self):
s1 = pd.Series(
np.arange(20, dtype=np.float64),
index=date_range("2020-01-01", periods=20, freq="B"),
)
s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15]]
# it works!
_, ax = mpl.pyplot.subplots()
s1.plot(ax=ax)
ax2 = s2.plot(style="g", ax=ax)
lines = ax2.get_lines()
# x-data is plain int64 business-day ordinals (not deprecated Period[B])
idx1 = lines[0].get_xdata()
idx2 = lines[1].get_xdata()
expected1 = np.array([conv.bday_count(ts) for ts in s1.index])
expected2 = np.array([conv.bday_count(ts) for ts in s2.index])
tm.assert_numpy_array_equal(idx1, expected1)
tm.assert_numpy_array_equal(idx2, expected2)
left, right = ax2.get_xlim()
assert left <= expected1[0]
assert right >= expected1[-1]
def test_mixed_freq_irregular_first(self):
s1 = pd.Series(
np.arange(20, dtype=np.float64), index=date_range("2020-01-01", periods=20)
)
s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15]]
_, ax = mpl.pyplot.subplots()
s2.plot(style="g", ax=ax)
s1.plot(ax=ax)
assert not hasattr(ax, "freq")
lines = ax.get_lines()
x1 = lines[0].get_xdata()
tm.assert_numpy_array_equal(x1, s2.index.astype(object).values)
x2 = lines[1].get_xdata()
tm.assert_numpy_array_equal(x2, s1.index.astype(object).values)
def test_mixed_freq_regular_first_df(self):
# GH 9852
s1 = pd.Series(
np.arange(20, dtype=np.float64),
index=date_range("2020-01-01", periods=20, freq="B"),
).to_frame()
s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15], :]
_, ax = mpl.pyplot.subplots()
s1.plot(ax=ax)
ax2 = s2.plot(style="g", ax=ax)
lines = ax2.get_lines()
# x-data is plain int64 business-day ordinals (not deprecated Period[B])
idx1 = lines[0].get_xdata()
idx2 = lines[1].get_xdata()
expected1 = np.array([conv.bday_count(ts) for ts in s1.index])
expected2 = np.array([conv.bday_count(ts) for ts in s2.index])
tm.assert_numpy_array_equal(idx1, expected1)
tm.assert_numpy_array_equal(idx2, expected2)
left, right = ax2.get_xlim()
assert left <= expected1[0]
assert right >= expected1[-1]
def test_mixed_freq_irregular_first_df(self):
# GH 9852
s1 = pd.Series(
np.arange(20, dtype=np.float64), index=date_range("2020-01-01", periods=20)
).to_frame()
s2 = s1.iloc[[0, 5, 10, 11, 12, 13, 14, 15], :]
_, ax = mpl.pyplot.subplots()
s2.plot(style="g", ax=ax)
s1.plot(ax=ax)
assert not hasattr(ax, "freq")
lines = ax.get_lines()
x1 = lines[0].get_xdata()
tm.assert_numpy_array_equal(x1, s2.index.astype(object).values)
x2 = lines[1].get_xdata()
tm.assert_numpy_array_equal(x2, s1.index.astype(object).values)
def test_bday_subplots_sharex_false(self):
# GH#64311 subplots=True with sharex=False previously raised
# AttributeError: only the first subplot received business-day freq
# info, and the int64 ordinal index carries no freq of its own.
idx = bdate_range("2020-01-01", periods=10)
df = pd.DataFrame(
np.arange(20, dtype=np.float64).reshape(10, 2),
index=idx,
columns=["a", "b"],
)
axes = df.plot(subplots=True, sharex=False)
expected = np.array([conv.bday_count(ts) for ts in idx])
for ax in axes:
assert ax.freq == "B"
tm.assert_numpy_array_equal(ax.get_lines()[0].get_xdata(), expected)
def test_mixed_freq_bday_then_higher(self):
# GH#64311 plotting a higher-frequency (hourly) series onto an existing
# business-day axis previously raised AttributeError: the stored BDay
# series has a plain int64 index with no .asfreq method.
bser = pd.Series(
np.arange(10, dtype=np.float64),
index=bdate_range("2020-01-01", periods=10),
)
hser = pd.Series(
np.arange(48, dtype=np.float64),
index=date_range("2020-01-01", periods=48, freq="h"),
)
_, ax = mpl.pyplot.subplots()
bser.plot(ax=ax)
hser.plot(ax=ax)
# both lines resolve onto the finer hourly grid
assert ax.freq == "h"
line_b, line_h = ax.get_lines()
idx_b = PeriodIndex.from_ordinals(line_b.get_xdata(), freq="h")
assert idx_b[0] == Period("2020-01-01 00:00", freq="h")
assert idx_b[-1] == Period("2020-01-14 00:00", freq="h")
idx_h = PeriodIndex.from_ordinals(line_h.get_xdata(), freq="h")
assert idx_h[0] == Period("2020-01-01 00:00", freq="h")
assert idx_h[-1] == Period("2020-01-02 23:00", freq="h")
# aligned starts -> shared first x-coordinate
assert line_b.get_xdata()[0] == line_h.get_xdata()[0]
def test_mixed_freq_bday_onto_lower(self):
# GH#64311 plotting BDay data onto an axis that already holds a
# lower-frequency (monthly) series previously left ax.freq clobbered to
# "B" before resampling, so the monthly line kept its month ordinals
# and the two lines ended up on incompatible scales.
mser = pd.Series(
np.arange(12, dtype=np.float64),
index=date_range("2020-01-01", periods=12, freq="ME"),
)
bser = pd.Series(
np.arange(10, dtype=np.float64),
index=bdate_range("2020-06-01", periods=10),
)
_, ax = mpl.pyplot.subplots()
mser.plot(ax=ax)
bser.plot(ax=ax)
# both lines share a common business-day ordinal scale
assert ax.freq == "B"
line_m, line_b = ax.get_lines()
# the monthly line is upsampled to the business-day ordinals of its
# (month-start) timestamps
expected_m = np.array(
[conv.bday_count(per.to_timestamp()) for per in mser.index.to_period("M")]
)
tm.assert_numpy_array_equal(line_m.get_xdata(), expected_m)
expected_b = np.array([conv.bday_count(ts) for ts in bser.index])
tm.assert_numpy_array_equal(line_b.get_xdata(), expected_b)
@pytest.mark.parametrize("freq", ["D", "h", "min", "s"])
def test_mixed_freq_bday_onto_finer_axis(self, freq):
# GH#64311, GH#66222 business-day data plotted onto an axis that
# already holds a daily-or-finer series raised TypeError("index type
# not supported"): the axis was formatted with the unresampled
# business-day ordinal index while ax.freq was the finer alias.
ser = pd.Series(
np.arange(30, dtype=np.float64),
index=date_range("2020-01-01", periods=30, freq=freq),
)
bidx = bdate_range("2020-01-01", periods=10)
bser = pd.Series(np.arange(10, dtype=np.float64), index=bidx)
_, ax = mpl.pyplot.subplots()
ser.plot(ax=ax)
bser.plot(ax=ax)
assert ax.freq == freq
# the business-day line lands on the ordinals of its own timestamps
expected = PeriodIndex(bidx, freq=freq).asi8
tm.assert_numpy_array_equal(ax.get_lines()[1].get_xdata(), expected)
def test_mixed_freq_bday_frame_onto_finer_axis(self):
# GH#65278 format_dateaxis runs once per axes, so it must use the index
# actually drawn on that axes rather than the frame-level index.
ser = pd.Series(
np.arange(30, dtype=np.float64),
index=date_range("2020-01-01", periods=30, freq="D"),
)
bidx = bdate_range("2020-01-01", periods=10)
df = pd.DataFrame(
np.arange(20, dtype=np.float64).reshape(10, 2),
index=bidx,
columns=["a", "b"],
)
_, ax = mpl.pyplot.subplots()
ser.plot(ax=ax)
df.plot(ax=ax)
assert ax.freq == "D"
expected = PeriodIndex(bidx, freq="D").asi8
for line in ax.get_lines()[1:]:
tm.assert_numpy_array_equal(line.get_xdata(), expected)
def test_mixed_freq_bday_onto_weekly_axis(self):
# GH#66222 business-day data plotted onto a weekly axis raised
# TypeError from resampling the int64 business-day ordinal index.
weekly_ser = pd.Series(
np.arange(8, dtype=np.float64),
index=date_range("2020-01-05", periods=8, freq="W-SUN"),
)
bser = pd.Series(
np.arange(30, dtype=np.float64),
index=bdate_range("2020-01-01", periods=30),
)
_, ax = mpl.pyplot.subplots()
weekly_ser.plot(ax=ax)
bser.plot(ax=ax)
assert ax.freq == "W-SUN"
# the business-day data is aggregated onto the weekly axis
expected = bser.resample("W-SUN").last().dropna()
line_b = ax.get_lines()[1]
tm.assert_numpy_array_equal(
line_b.get_xdata(), PeriodIndex(expected.index, freq="W-SUN").asi8
)
tm.assert_numpy_array_equal(line_b.get_ydata(), expected.to_numpy())
def test_plain_int_index_onto_ts_axis_raises(self):
# GH#64311 an integer index only means business-day ordinals when it
# came from the BDay conversion; a genuine int-index series overlaid
# on a ts axis must raise (as before) rather than be reinterpreted as
# business days and rescale the existing line.
mser = pd.Series(
np.arange(12, dtype=np.float64),
index=period_range("2020-01", periods=12, freq="M"),
)
iser = pd.Series(np.arange(10, dtype=np.float64))
_, ax = mpl.pyplot.subplots()
mser.plot(ax=ax)
with pytest.raises(TypeError, match="index type not supported"):
iser.plot(ax=ax)
def test_scatter_plain_int_x_onto_ts_axis(self):
# GH#64311 scatter with a plain integer x column onto an existing ts
# axis must not reinterpret the ints as business-day ordinals (which
# rescaled the existing line and clobbered ax.freq).
mser = pd.Series(
np.arange(12, dtype=np.float64),
index=period_range("2020-01", periods=12, freq="M"),
)
df = pd.DataFrame({"x": np.arange(10), "y": np.arange(10, dtype=np.float64)})
_, ax = mpl.pyplot.subplots()
mser.plot(ax=ax)
expected = ax.get_lines()[0].get_xdata().copy()
df.plot.scatter(x="x", y="y", ax=ax)
assert ax.freq == "M"
tm.assert_numpy_array_equal(ax.get_lines()[0].get_xdata(), expected)
def test_mixed_freq_hf_first(self):
idxh = date_range("1/1/1999", periods=365, freq="D")
idxl = date_range("1/1/1999", periods=12, freq="ME")
high = pd.Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
low = pd.Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
_, ax = mpl.pyplot.subplots()
high.plot(ax=ax)
low.plot(ax=ax)
for line in ax.get_lines():
assert PeriodIndex.from_ordinals(line.get_xdata(), freq=ax.freq).freq == "D"
def test_mixed_freq_alignment(self):
ts_ind = date_range("2012-01-01 13:00", "2012-01-02", freq="h")
ts_data = np.random.default_rng(2).standard_normal(12)
ts = pd.Series(ts_data, index=ts_ind)
ts2 = ts.asfreq("min").interpolate()
_, ax = mpl.pyplot.subplots()
ax = ts.plot(ax=ax)
ts2.plot(style="r", ax=ax)
assert ax.lines[0].get_xdata()[0] == ax.lines[1].get_xdata()[0]
def test_mixed_freq_lf_first(self):
idxh = date_range("1/1/1999", periods=365, freq="D")
idxl = date_range("1/1/1999", periods=12, freq="ME")
high = pd.Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
low = pd.Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
_, ax = mpl.pyplot.subplots()
low.plot(legend=True, ax=ax)
high.plot(legend=True, ax=ax)
for line in ax.get_lines():
assert PeriodIndex.from_ordinals(line.get_xdata(), freq=ax.freq).freq == "D"
leg = ax.get_legend()
assert len(leg.texts) == 2
mpl.pyplot.close(ax.get_figure())
def test_mixed_freq_lf_first_hourly(self):
idxh = date_range("1/1/1999", periods=240, freq="min")
idxl = date_range("1/1/1999", periods=4, freq="h")
high = pd.Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
low = pd.Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
_, ax = mpl.pyplot.subplots()
low.plot(ax=ax)
high.plot(ax=ax)
for line in ax.get_lines():
assert (
PeriodIndex.from_ordinals(line.get_xdata(), freq=ax.freq).freq == "min"
)
@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning")
def test_mixed_freq_irreg_period(self):
ts = pd.Series(
np.arange(30, dtype=np.float64), index=date_range("2020-01-01", periods=30)
)
irreg = ts.iloc[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 18, 29]]
msg = r"PeriodDtype\[B\] is deprecated"
with tm.assert_produces_warning(FutureWarning, match=msg):
rng = period_range("1/3/2000", periods=30, freq="B")
ps = pd.Series(np.random.default_rng(2).standard_normal(len(rng)), rng)
_, ax = mpl.pyplot.subplots()
irreg.plot(ax=ax)
ps.plot(ax=ax)
def test_mixed_freq_shared_ax(self):
# GH13341, using sharex=True
idx1 = date_range("2015-01-01", periods=3, freq="ME")
idx2 = idx1[:1].union(idx1[2:])
s1 = pd.Series(range(len(idx1)), idx1)
s2 = pd.Series(range(len(idx2)), idx2)
_, (ax1, ax2) = mpl.pyplot.subplots(nrows=2, sharex=True)
s1.plot(ax=ax1)
s2.plot(ax=ax2)
assert ax1.freq == "M"
assert ax2.freq == "M"
assert ax1.lines[0].get_xydata()[0, 0] == ax2.lines[0].get_xydata()[0, 0]
def test_mixed_freq_shared_ax_twin_x(self):
# GH13341, using sharex=True
idx1 = date_range("2015-01-01", periods=3, freq="ME")
idx2 = idx1[:1].union(idx1[2:])
s1 = pd.Series(range(len(idx1)), idx1)
s2 = pd.Series(range(len(idx2)), idx2)
# using twinx
_, ax1 = mpl.pyplot.subplots()
ax2 = ax1.twinx()
s1.plot(ax=ax1)
s2.plot(ax=ax2)
assert ax1.lines[0].get_xydata()[0, 0] == ax2.lines[0].get_xydata()[0, 0]
@pytest.mark.xfail(reason="TODO (GH14330, GH14322)")
def test_mixed_freq_shared_ax_twin_x_irregular_first(self):
# GH13341, using sharex=True
idx1 = date_range("2015-01-01", periods=3, freq="ME")
idx2 = idx1[:1].union(idx1[2:])
s1 = pd.Series(range(len(idx1)), idx1)
s2 = pd.Series(range(len(idx2)), idx2)
_, ax1 = mpl.pyplot.subplots()
ax2 = ax1.twinx()
s2.plot(ax=ax1)
s1.plot(ax=ax2)
assert ax1.lines[0].get_xydata()[0, 0] == ax2.lines[0].get_xydata()[0, 0]
def test_nat_handling(self):
_, ax = mpl.pyplot.subplots()
dti = DatetimeIndex(["2015-01-01", pd.NaT, "2015-01-03"])
s = pd.Series(range(len(dti)), dti)
s.plot(ax=ax)
xdata = ax.get_lines()[0].get_xdata()
# plot x data is bounded by index values
assert s.index.min() <= pd.Series(xdata).min()
assert pd.Series(xdata).max() <= s.index.max()
def test_to_weekly_resampling_disallow_how_kwd(self):
idxh = date_range("1/1/1999", periods=52, freq="W")
idxl = date_range("1/1/1999", periods=12, freq="ME")
high = pd.Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
low = pd.Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
_, ax = mpl.pyplot.subplots()
high.plot(ax=ax)
msg = (
"'how' is not a valid keyword for plotting functions. If plotting "
"multiple objects on shared axes, resample manually first."
)
with pytest.raises(ValueError, match=msg):
low.plot(ax=ax, how="foo")
def test_to_weekly_resampling(self):
idxh = date_range("1/1/1999", periods=52, freq="W")
idxl = date_range("1/1/1999", periods=12, freq="ME")
high = pd.Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
low = pd.Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
_, ax = mpl.pyplot.subplots()
high.plot(ax=ax)
low.plot(ax=ax)
for line in ax.get_lines():
assert (
PeriodIndex.from_ordinals(line.get_xdata(), freq=ax.freq).freq
== idxh.freq
)
def test_from_weekly_resampling(self):
idxh = date_range("1/1/1999", periods=52, freq="W")
idxl = date_range("1/1/1999", periods=12, freq="ME")
high = pd.Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
low = pd.Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
_, ax = mpl.pyplot.subplots()
low.plot(ax=ax)
high.plot(ax=ax)
expected_h = idxh.to_period().asi8.astype(np.float64)
expected_l = np.array(
[1514, 1519, 1523, 1527, 1531, 1536, 1540, 1544, 1549, 1553, 1558, 1562],
dtype=np.float64,
)
for line in ax.get_lines():
assert (
PeriodIndex.from_ordinals(line.get_xdata(), freq=ax.freq).freq
== idxh.freq
)
xdata = line.get_xdata(orig=False)
if len(xdata) == 12: # idxl lines
tm.assert_numpy_array_equal(xdata, expected_l)
else:
tm.assert_numpy_array_equal(xdata, expected_h)
@pytest.mark.parametrize("kind1, kind2", [("line", "area"), ("area", "line")])
def test_from_resampling_area_line_mixed(self, kind1, kind2):
idxh = date_range("1/1/1999", periods=52, freq="W")
idxl = date_range("1/1/1999", periods=12, freq="ME")
high = pd.DataFrame(
np.random.default_rng(2).random((len(idxh), 3)),
index=idxh,
columns=[0, 1, 2],
)
low = pd.DataFrame(
np.random.default_rng(2).random((len(idxl), 3)),
index=idxl,
columns=[0, 1, 2],
)
_, ax = mpl.pyplot.subplots()
low.plot(kind=kind1, stacked=True, ax=ax)
high.plot(kind=kind2, stacked=True, ax=ax)
# check low dataframe result
expected_x = np.array(
[
1514,
1519,
1523,
1527,
1531,
1536,
1540,
1544,
1549,
1553,
1558,
1562,
],
dtype=np.float64,
)
expected_y = np.zeros(len(expected_x), dtype=np.float64)
for i in range(3):
line = ax.lines[i]
assert (
PeriodIndex.from_ordinals(line.get_xdata(), freq=ax.freq).freq
== idxh.freq
)
tm.assert_numpy_array_equal(line.get_xdata(orig=False), expected_x)
# check stacked values are correct
expected_y += low[i].values
tm.assert_numpy_array_equal(line.get_ydata(orig=False), expected_y)
# check high dataframe result
expected_x = idxh.to_period().asi8.astype(np.float64)
expected_y = np.zeros(len(expected_x), dtype=np.float64)
for i in range(3):
line = ax.lines[3 + i]
assert (
PeriodIndex.from_ordinals(line.get_xdata(), freq=ax.freq).freq
== idxh.freq
)
tm.assert_numpy_array_equal(line.get_xdata(orig=False), expected_x)
expected_y += high[i].values
tm.assert_numpy_array_equal(line.get_ydata(orig=False), expected_y)
@pytest.mark.parametrize("kind1, kind2", [("line", "area"), ("area", "line")])
def test_from_resampling_area_line_mixed_high_to_low(self, kind1, kind2):
idxh = date_range("1/1/1999", periods=52, freq="W")
idxl = date_range("1/1/1999", periods=12, freq="ME")
high = pd.DataFrame(
np.random.default_rng(2).random((len(idxh), 3)),
index=idxh,
columns=[0, 1, 2],
)
low = pd.DataFrame(
np.random.default_rng(2).random((len(idxl), 3)),
index=idxl,
columns=[0, 1, 2],
)
_, ax = mpl.pyplot.subplots()
high.plot(kind=kind1, stacked=True, ax=ax)
low.plot(kind=kind2, stacked=True, ax=ax)
# check high dataframe result
expected_x = idxh.to_period().asi8.astype(np.float64)
expected_y = np.zeros(len(expected_x), dtype=np.float64)
for i in range(3):
line = ax.lines[i]
assert (
PeriodIndex.from_ordinals(line.get_xdata(), freq=ax.freq).freq
== idxh.freq
)
tm.assert_numpy_array_equal(line.get_xdata(orig=False), expected_x)
expected_y += high[i].values
tm.assert_numpy_array_equal(line.get_ydata(orig=False), expected_y)
# check low dataframe result
expected_x = np.array(
[
1514,
1519,
1523,
1527,
1531,
1536,
1540,
1544,
1549,
1553,
1558,
1562,
],
dtype=np.float64,
)
expected_y = np.zeros(len(expected_x), dtype=np.float64)
for i in range(3):
lines = ax.lines[3 + i]
assert (
PeriodIndex.from_ordinals(lines.get_xdata(), freq=ax.freq).freq
== idxh.freq
)
tm.assert_numpy_array_equal(lines.get_xdata(orig=False), expected_x)
expected_y += low[i].values
tm.assert_numpy_array_equal(lines.get_ydata(orig=False), expected_y)
def test_mixed_freq_second_millisecond(self):
# GH 7772, GH 7760
idxh = date_range("2014-07-01 09:00", freq="s", periods=5)
idxl = date_range("2014-07-01 09:00", freq="100ms", periods=50)
high = pd.Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
low = pd.Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
# high to low
_, ax = mpl.pyplot.subplots()
high.plot(ax=ax)
low.plot(ax=ax)
assert len(ax.get_lines()) == 2
for line in ax.get_lines():
assert (
PeriodIndex.from_ordinals(line.get_xdata(), freq=ax.freq).freq
== "100ms"
)
def test_mixed_freq_second_millisecond_low_to_high(self):
# GH 7772, GH 7760
idxh = date_range("2014-07-01 09:00", freq="s", periods=5)
idxl = date_range("2014-07-01 09:00", freq="100ms", periods=50)
high = pd.Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
low = pd.Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
# low to high
_, ax = mpl.pyplot.subplots()
low.plot(ax=ax)
high.plot(ax=ax)
assert len(ax.get_lines()) == 2
for line in ax.get_lines():
assert (
PeriodIndex.from_ordinals(line.get_xdata(), freq=ax.freq).freq
== "100ms"
)
def test_irreg_dtypes(self):
# date
idx = [date(2000, 1, 1), date(2000, 1, 5), date(2000, 1, 20)]
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((len(idx), 3)),
pd.Index(idx, dtype=object),
)
_check_plot_works(df.plot)
def test_irreg_dtypes_dt64(self):
# np.datetime64
idx = date_range("1/1/2000", periods=10)
idx = idx[[0, 2, 5, 9]].astype(object)
df = pd.DataFrame(np.random.default_rng(2).standard_normal((len(idx), 3)), idx)
_, ax = mpl.pyplot.subplots()
_check_plot_works(df.plot, ax=ax)
def test_time(self):
t = datetime(1, 1, 1, 3, 30, 0)
deltas = np.random.default_rng(2).integers(1, 20, 3).cumsum()
ts = np.array([(t + timedelta(minutes=int(x))).time() for x in deltas])
df = pd.DataFrame(
{
"a": np.random.default_rng(2).standard_normal(len(ts)),
"b": np.random.default_rng(2).standard_normal(len(ts)),
},
index=ts,
)
_, ax = mpl.pyplot.subplots()
df.plot(ax=ax)
# verify tick labels
ticks = ax.get_xticks()
labels = ax.get_xticklabels()
for _tick, _label in zip(ticks, labels, strict=True):
m, s = divmod(int(_tick), 60)
h, m = divmod(m, 60)
rs = _label.get_text()
if len(rs) > 0:
if s != 0:
xp = time(h, m, s).strftime("%H:%M:%S")
else:
xp = time(h, m, s).strftime("%H:%M")
assert xp == rs
def test_time_change_xlim(self):
t = datetime(1, 1, 1, 3, 30, 0)
deltas = np.random.default_rng(2).integers(1, 20, 3).cumsum()
ts = np.array([(t + timedelta(minutes=int(x))).time() for x in deltas])
df = pd.DataFrame(
{
"a": np.random.default_rng(2).standard_normal(len(ts)),
"b": np.random.default_rng(2).standard_normal(len(ts)),
},
index=ts,
)
_, ax = mpl.pyplot.subplots()
df.plot(ax=ax)
# verify tick labels
ticks = ax.get_xticks()
labels = ax.get_xticklabels()
for _tick, _label in zip(ticks, labels, strict=True):
m, s = divmod(int(_tick), 60)
h, m = divmod(m, 60)
rs = _label.get_text()
if len(rs) > 0:
if s != 0:
xp = time(h, m, s).strftime("%H:%M:%S")
else:
xp = time(h, m, s).strftime("%H:%M")
assert xp == rs
# change xlim
ax.set_xlim("1:30", "5:00")
# check tick labels again
ticks = ax.get_xticks()
labels = ax.get_xticklabels()
for _tick, _label in zip(ticks, labels, strict=True):
m, s = divmod(int(_tick), 60)
h, m = divmod(m, 60)
rs = _label.get_text()
if len(rs) > 0:
if s != 0:
xp = time(h, m, s).strftime("%H:%M:%S")
else:
xp = time(h, m, s).strftime("%H:%M")
assert xp == rs
def test_time_musec(self):
t = datetime(1, 1, 1, 3, 30, 0)
deltas = np.random.default_rng(2).integers(1, 20, 3).cumsum()
ts = np.array([(t + timedelta(microseconds=int(x))).time() for x in deltas])
df = pd.DataFrame(
{
"a": np.random.default_rng(2).standard_normal(len(ts)),
"b": np.random.default_rng(2).standard_normal(len(ts)),
},
index=ts,
)
_, ax = mpl.pyplot.subplots()
ax = df.plot(ax=ax)
# verify tick labels
ticks = ax.get_xticks()
labels = ax.get_xticklabels()
for _tick, _label in zip(ticks, labels, strict=True):
m, s = divmod(int(_tick), 60)
us = round((_tick - int(_tick)) * 1e6)
h, m = divmod(m, 60)
rs = _label.get_text()
if len(rs) > 0:
if (us % 1000) != 0:
xp = time(h, m, s, us).strftime("%H:%M:%S.%f")
elif (us // 1000) != 0:
xp = time(h, m, s, us).strftime("%H:%M:%S.%f")[:-3]
elif s != 0:
xp = time(h, m, s, us).strftime("%H:%M:%S")
else:
xp = time(h, m, s, us).strftime("%H:%M")
assert xp == rs
def test_secondary_upsample(self):
idxh = date_range("1/1/1999", periods=365, freq="D")
idxl = date_range("1/1/1999", periods=12, freq="ME")
high = pd.Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh)
low = pd.Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl)
_, ax = mpl.pyplot.subplots()
low.plot(ax=ax)
ax = high.plot(secondary_y=True, ax=ax)
for line in ax.get_lines():
assert PeriodIndex.from_ordinals(line.get_xdata(), freq=ax.freq).freq == "D"
assert hasattr(ax, "left_ax")
assert not hasattr(ax, "right_ax")
for line in ax.left_ax.get_lines():
assert PeriodIndex.from_ordinals(line.get_xdata(), freq=ax.freq).freq == "D"
def test_secondary_legend(self):
fig = mpl.pyplot.figure()
ax = fig.add_subplot(211)
# ts
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((10, 4)),
columns=pd.Index(list("ABCD"), dtype=object),
index=date_range("2000-01-01", periods=10, freq="B"),
)
df.plot(secondary_y=["A", "B"], ax=ax)
leg = ax.get_legend()
assert len(leg.get_lines()) == 4
assert leg.get_texts()[0].get_text() == "A (right)"
assert leg.get_texts()[1].get_text() == "B (right)"
assert leg.get_texts()[2].get_text() == "C"
assert leg.get_texts()[3].get_text() == "D"
assert ax.right_ax.get_legend() is None
colors = set()
for line in leg.get_lines():
colors.add(line.get_color())
# TODO: color cycle problems
assert len(colors) == 4
def test_secondary_legend_right(self):
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((10, 4)),
columns=pd.Index(list("ABCD"), dtype=object),
index=date_range("2000-01-01", periods=10, freq="B"),
)
fig = mpl.pyplot.figure()
ax = fig.add_subplot(211)
df.plot(secondary_y=["A", "C"], mark_right=False, ax=ax)
leg = ax.get_legend()
assert len(leg.get_lines()) == 4
assert leg.get_texts()[0].get_text() == "A"
assert leg.get_texts()[1].get_text() == "B"
assert leg.get_texts()[2].get_text() == "C"
assert leg.get_texts()[3].get_text() == "D"
def test_secondary_legend_bar(self):
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((10, 4)),
columns=pd.Index(list("ABCD"), dtype=object),
index=date_range("2000-01-01", periods=10, freq="B"),
)
fig, ax = mpl.pyplot.subplots()
df.plot(kind="bar", secondary_y=["A"], ax=ax)
leg = ax.get_legend()
assert leg.get_texts()[0].get_text() == "A (right)"
assert leg.get_texts()[1].get_text() == "B"
def test_secondary_legend_bar_right(self):
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((10, 4)),
columns=pd.Index(list("ABCD"), dtype=object),
index=date_range("2000-01-01", periods=10, freq="B"),
)
fig, ax = mpl.pyplot.subplots()
df.plot(kind="bar", secondary_y=["A"], mark_right=False, ax=ax)
leg = ax.get_legend()
assert leg.get_texts()[0].get_text() == "A"
assert leg.get_texts()[1].get_text() == "B"
def test_secondary_legend_multi_col(self):
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((10, 4)),
columns=pd.Index(list("ABCD"), dtype=object),
index=date_range("2000-01-01", periods=10, freq="B"),
)
fig = mpl.pyplot.figure()
ax = fig.add_subplot(211)
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((10, 4)),
columns=pd.Index(list("ABCD"), dtype=object),
index=date_range("2000-01-01", periods=10, freq="B"),
)
ax = df.plot(secondary_y=["C", "D"], ax=ax)
leg = ax.get_legend()
assert len(leg.get_lines()) == 4
assert ax.right_ax.get_legend() is None
colors = set()
for line in leg.get_lines():
colors.add(line.get_color())
# TODO: color cycle problems
assert len(colors) == 4
def test_secondary_legend_nonts(self):
# non-ts
df = pd.DataFrame(
1.1 * np.arange(40).reshape((10, 4)),
columns=pd.Index(list("ABCD"), dtype=object),
index=pd.Index([f"i-{i}" for i in range(10)], dtype=object),
)
fig = mpl.pyplot.figure()
ax = fig.add_subplot(211)
ax = df.plot(secondary_y=["A", "B"], ax=ax)
leg = ax.get_legend()
assert len(leg.get_lines()) == 4
assert ax.right_ax.get_legend() is None
colors = set()
for line in leg.get_lines():
colors.add(line.get_color())
# TODO: color cycle problems
assert len(colors) == 4
def test_secondary_legend_nonts_multi_col(self):
# non-ts
df = pd.DataFrame(
1.1 * np.arange(40).reshape((10, 4)),
columns=pd.Index(list("ABCD"), dtype=object),
index=pd.Index([f"i-{i}" for i in range(10)], dtype=object),
)
fig = mpl.pyplot.figure()
ax = fig.add_subplot(211)
ax = df.plot(secondary_y=["C", "D"], ax=ax)
leg = ax.get_legend()
assert len(leg.get_lines()) == 4
assert ax.right_ax.get_legend() is None
colors = set()
for line in leg.get_lines():
colors.add(line.get_color())
# TODO: color cycle problems
assert len(colors) == 4
@pytest.mark.xfail(reason="Api changed in 3.6.0")
def test_format_date_axis(self):
rng = date_range("1/1/2012", periods=12, freq="ME")
df = pd.DataFrame(np.random.default_rng(2).standard_normal((len(rng), 3)), rng)
_, ax = mpl.pyplot.subplots()
ax = df.plot(ax=ax)
xaxis = ax.get_xaxis()
for line in xaxis.get_ticklabels():
if len(line.get_text()) > 0:
assert line.get_rotation() == 30
def test_ax_plot(self):
x = date_range(start="2012-01-02", periods=10, freq="D")
y = list(range(len(x)))
_, ax = mpl.pyplot.subplots()
lines = ax.plot(x, y, label="Y")
tm.assert_index_equal(DatetimeIndex(lines[0].get_xdata()), x, check_freq=False)
def test_mpl_nopandas(self):
dates = [date(2008, 12, 31), date(2009, 1, 31)]
values1 = np.arange(10.0, 11.0, 0.5)
values2 = np.arange(11.0, 12.0, 0.5)
_, ax = mpl.pyplot.subplots()
(
line1,
line2,
) = ax.plot(
[x.toordinal() for x in dates],
values1,
"-",
[x.toordinal() for x in dates],
values2,
"-",
linewidth=4,
)
exp = np.array([x.toordinal() for x in dates], dtype=np.float64)
tm.assert_numpy_array_equal(line1.get_xydata()[:, 0], exp)
tm.assert_numpy_array_equal(line2.get_xydata()[:, 0], exp)
def test_irregular_ts_shared_ax_xlim(self):
# GH 2960
ts = pd.Series(
np.arange(20, dtype=np.float64), index=date_range("2020-01-01", periods=20)
)
ts_irregular = ts.iloc[[1, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18]]
# plot the left section of the irregular series, then the right section
_, ax = mpl.pyplot.subplots()
ts_irregular[:5].plot(ax=ax)
ts_irregular[5:].plot(ax=ax)
# check that axis limits are correct
left, right = ax.get_xlim()
assert left <= conv.DatetimeConverter.convert(ts_irregular.index.min(), "", ax)
assert right >= conv.DatetimeConverter.convert(ts_irregular.index.max(), "", ax)
def test_secondary_y_non_ts_xlim(self):
# GH 3490 - non-timeseries with secondary y
index_1 = [1, 2, 3, 4]
index_2 = [5, 6, 7, 8]
s1 = pd.Series(1, index=index_1)
s2 = pd.Series(2, index=index_2)
_, ax = mpl.pyplot.subplots()
s1.plot(ax=ax)
left_before, right_before = ax.get_xlim()
s2.plot(secondary_y=True, ax=ax)
left_after, right_after = ax.get_xlim()
assert left_before >= left_after
assert right_before < right_after
def test_secondary_y_regular_ts_xlim(self):
# GH 3490 - regular-timeseries with secondary y
index_1 = date_range(start="2000-01-01", periods=4, freq="D")
index_2 = date_range(start="2000-01-05", periods=4, freq="D")
s1 = pd.Series(1, index=index_1)
s2 = pd.Series(2, index=index_2)
_, ax = mpl.pyplot.subplots()
s1.plot(ax=ax)
left_before, right_before = ax.get_xlim()
s2.plot(secondary_y=True, ax=ax)
left_after, right_after = ax.get_xlim()
assert left_before >= left_after
assert right_before < right_after
def test_secondary_y_mixed_freq_ts_xlim(self):
# GH 3490 - mixed frequency timeseries with secondary y
rng = date_range("2000-01-01", periods=10, freq="min")
ts = pd.Series(1, index=rng)
_, ax = mpl.pyplot.subplots()
ts.plot(ax=ax)
left_before, right_before = ax.get_xlim()
ts.resample("D").mean().plot(secondary_y=True, ax=ax)
left_after, right_after = ax.get_xlim()
# a downsample should not have changed either limit
assert left_before == left_after
assert right_before == right_after
def test_secondary_y_irregular_ts_xlim(self):
# GH 3490 - irregular-timeseries with secondary y
ts = pd.Series(
np.arange(20, dtype=np.float64), index=date_range("2020-01-01", periods=20)
)
ts_irregular = ts.iloc[[1, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18]]
_, ax = mpl.pyplot.subplots()
ts_irregular[:5].plot(ax=ax)
# plot higher-x values on secondary axis
ts_irregular[5:].plot(secondary_y=True, ax=ax)
# ensure secondary limits aren't overwritten by plot on primary
ts_irregular[:5].plot(ax=ax)
left, right = ax.get_xlim()
assert left <= conv.DatetimeConverter.convert(ts_irregular.index.min(), "", ax)
assert right >= conv.DatetimeConverter.convert(ts_irregular.index.max(), "", ax)
def test_plot_outofbounds_datetime(self):
# 2579 - checking this does not raise
values = [date(1677, 1, 1), date(1677, 1, 2)]
_, ax = mpl.pyplot.subplots()
ax.plot(values)
values = [datetime(1677, 1, 1, 12), datetime(1677, 1, 2, 12)]
ax.plot(values)
def test_format_timedelta_ticks_narrow(self):
expected_labels = [f"00:00:00.0000000{i:0>2d}" for i in np.arange(10)]
rng = timedelta_range("0", periods=10, freq="ns")
df = pd.DataFrame(np.random.default_rng(2).standard_normal((len(rng), 3)), rng)
_, ax = mpl.pyplot.subplots()
df.plot(fontsize=2, ax=ax)
mpl.pyplot.draw()
labels = ax.get_xticklabels()
result_labels = [x.get_text() for x in labels]
assert len(result_labels) == len(expected_labels)
assert result_labels == expected_labels
def test_format_timedelta_ticks_wide(self, unit):
expected_labels = [
"00:00:00",
"1 days 03:46:40",
"2 days 07:33:20",
"3 days 11:20:00",
"4 days 15:06:40",
"5 days 18:53:20",
"6 days 22:40:00",
"8 days 02:26:40",
"9 days 06:13:20",
]
rng = timedelta_range("0", periods=10, freq="1 D", unit=unit)
df = pd.DataFrame(np.random.default_rng(2).standard_normal((len(rng), 3)), rng)
_, ax = mpl.pyplot.subplots()
ax = df.plot(fontsize=2, ax=ax)
mpl.pyplot.draw()
labels = ax.get_xticklabels()
result_labels = [x.get_text() for x in labels]
assert len(result_labels) == len(expected_labels)
assert result_labels == expected_labels
def test_irregular_timedelta_index_labels(self):
# GH#18910 a sub-millisecond TimedeltaIndex with no inferred freq must
# still get x-axis tick labels
rng = pd.to_timedelta(np.arange(0, 1, 1e-4), unit="s")
df = pd.DataFrame(np.random.default_rng(2).standard_normal((len(rng), 3)), rng)
_, ax = mpl.pyplot.subplots()
df.plot(ax=ax)
mpl.pyplot.draw()
labels = [x.get_text() for x in ax.get_xticklabels() if x.get_text().strip()]
assert labels
# every label shown corresponds to an actual index entry
assert set(labels) <= {str(td) for td in rng}
def test_timedelta_plot(self):
# test issue #8711
s = pd.Series(range(5), timedelta_range("1day", periods=5))
_, ax = mpl.pyplot.subplots()
_check_plot_works(s.plot, ax=ax)
def test_timedelta_long_period(self):
# test long period
index = timedelta_range("1 day 2 hr 30 min 10 s", periods=10, freq="1 D")
s = pd.Series(np.random.default_rng(2).standard_normal(len(index)), index)
_, ax = mpl.pyplot.subplots()
_check_plot_works(s.plot, ax=ax)
def test_timedelta_short_period(self):
# test short period
index = timedelta_range("1 day 2 hr 30 min 10 s", periods=10, freq="1 ns")
s = pd.Series(np.random.default_rng(2).standard_normal(len(index)), index)
_, ax = mpl.pyplot.subplots()
_check_plot_works(s.plot, ax=ax)
def test_hist(self):
# https://github.com/matplotlib/matplotlib/issues/8459
rng = date_range("1/1/2011", periods=10, freq="h")
x = rng
w1 = np.arange(0, 1, 0.1)
w2 = np.arange(0, 1, 0.1)[::-1]
_, ax = mpl.pyplot.subplots()
ax.hist([x, x], weights=[w1, w2])
def test_overlapping_datetime(self):
# GB 6608
s1 = pd.Series(
[1, 2, 3],
index=[
datetime(1995, 12, 31),
datetime(2000, 12, 31),
datetime(2005, 12, 31),
],
)
s2 = pd.Series(
[1, 2, 3],
index=[
datetime(1997, 12, 31),
datetime(2003, 12, 31),
datetime(2008, 12, 31),
],
)
# plot first series, then add the second series to those axes,
# then try adding the first series again
_, ax = mpl.pyplot.subplots()
s1.plot(ax=ax)
s2.plot(ax=ax)
s1.plot(ax=ax)
def test_add_matplotlib_datetime64(self):
# GH#9053 - ensure that a plot with PeriodConverter still understands
# datetime64 data
s = pd.Series(
np.random.default_rng(2).standard_normal(10),
index=date_range("1970-01-02", periods=10),
)
ax = s.plot()
ax.plot(s.index, s.values, color="g")
l1, l2 = ax.lines
tm.assert_numpy_array_equal(l1.get_xydata(), l2.get_xydata())
def test_matplotlib_scatter_datetime64(self):
# https://github.com/matplotlib/matplotlib/issues/11391
df = pd.DataFrame(np.random.default_rng(2).random((10, 2)), columns=["x", "y"])
df["time"] = date_range("2018-01-01", periods=10, freq="D")
_, ax = mpl.pyplot.subplots()
ax.scatter(x="time", y="y", data=df)
mpl.pyplot.draw()
label = ax.get_xticklabels()[0]
expected = "2018-01-01"
assert label.get_text() == expected
def test_check_xticks_rot(self):
# https://github.com/pandas-dev/pandas/issues/29460
# regular time series
x = pd.to_datetime(["2020-05-01", "2020-05-02", "2020-05-03"])
df = pd.DataFrame({"x": x, "y": [1, 2, 3]})
axes = df.plot(x="x", y="y")
_check_ticks_props(axes, xrot=0)
def test_check_xticks_rot_irregular(self):
# irregular time series
x = pd.to_datetime(["2020-05-01", "2020-05-02", "2020-05-04"])
df = pd.DataFrame({"x": x, "y": [1, 2, 3]})
axes = df.plot(x="x", y="y")
_check_ticks_props(axes, xrot=30)
def test_check_xticks_rot_use_idx(self):
# irregular time series
x = pd.to_datetime(["2020-05-01", "2020-05-02", "2020-05-04"])
df = pd.DataFrame({"x": x, "y": [1, 2, 3]})
# use timeseries index or not
axes = df.set_index("x").plot(y="y", use_index=True)
_check_ticks_props(axes, xrot=30)
axes = df.set_index("x").plot(y="y", use_index=False)
_check_ticks_props(axes, xrot=0)
def test_check_xticks_rot_sharex(self):
# irregular time series
x = pd.to_datetime(["2020-05-01", "2020-05-02", "2020-05-04"])
df = pd.DataFrame({"x": x, "y": [1, 2, 3]})
# separate subplots
axes = df.plot(x="x", y="y", subplots=True, sharex=True)
_check_ticks_props(axes, xrot=30)
axes = df.plot(x="x", y="y", subplots=True, sharex=False)
_check_ticks_props(axes, xrot=0)
@pytest.mark.parametrize(
"idx",
[
date_range("2020-01-01", periods=5),
date_range("2020-01-01", periods=5, tz="UTC"),
timedelta_range("1 day", periods=5, freq="D"),
period_range("2020-01-01", periods=5, freq="D"),
pd.Index([date(2000, 1, i) for i in [1, 3, 6, 20, 22]], dtype=object),
range(5),
],
)
def test_pickle_fig(self, temp_file, frame_or_series, idx):
# GH18439, GH#24088, statsmodels#4772
df = frame_or_series(range(5), index=idx)
fig, ax = plt.subplots(1, 1)
df.plot(ax=ax)
with temp_file.open(mode="wb") as path:
pickle.dump(fig, path)
@pytest.mark.parametrize("freq", ["D", "B"])
def test_bar_plot_with_datetime_index_uses_date_formatter(self, freq):
# GH#1918 - bar plots use the dynamic date formatter like line plots
df = pd.DataFrame(
np.random.default_rng(2).standard_normal((10, 2)),
index=date_range("2020-01-01", periods=10, freq=freq),
columns=["A", "B"],
)
with tm.assert_produces_warning(None):
ax = df.plot(kind="bar")
assert isinstance(
ax.get_xaxis().get_major_formatter(), conv.TimeSeries_DateFormatter
)
# the formatted labels correspond to the actual dates, not ordinals
# misinterpreted relative to the axis origin
ax.get_figure().canvas.draw()
labels = [t.get_text() for t in ax.get_xticklabels() if t.get_text()]
assert labels
assert any("2020" in label for label in labels)
assert not any("1970" in label for label in labels)
@pytest.mark.parametrize(
"freq", ["D", "W", "ME", "QE", "YE", "h", "2D", "3h", "5D", "2W", "10min"]
)
def test_bar_plot_date_axis_ticks_land_on_bars(self, freq):
# GH#1918 - every drawn tick must label a timestamp that has a bar
s = pd.Series(
np.arange(10.0), index=date_range("2020-01-06", periods=10, freq=freq)
)
ax = s.plot(kind="bar")
ax.get_figure().canvas.draw()
lo, hi = ax.get_xlim()
bars = {round(p.get_x() + p.get_width() / 2) for p in ax.patches}
drawn = [int(t) for t in ax.get_xticks() if lo <= t <= hi]
assert drawn
assert set(drawn) <= bars
# the minor ticks carry labels of their own, so they have to land on
# bars as well
minor = [int(t) for t in ax.get_xticks(minor=True) if lo <= t <= hi]
assert set(minor) <= bars
@pytest.mark.parametrize("freq", ["2B", "3B", "2ME", "2QE", "2YE"])
def test_bar_plot_unanchorable_freq_keeps_fixed_ticks(self, freq):
# GH#1918 - two frequencies the tick grid cannot be aligned to.
# Period[B] is deprecated, so the period alias for business days drops
# the multiplier and '3B' resolves to BusinessDay(1), stepping one
# business day at a time past bars that are three apart; and the
# monthly, quarterly and annual finders walk every period regardless of
# the multiplier, putting their minor ticks between the bars
s = pd.Series(
np.arange(10.0), index=date_range("2020-01-06", periods=10, freq=freq)
)
ax = s.plot(kind="bar")
assert not isinstance(
ax.get_xaxis().get_major_formatter(), conv.TimeSeries_DateFormatter
)
def test_bar_plot_date_axis_converter_is_usable(self):
# GH#1918 - format_dateaxis installs a PeriodConverter that reads the
# freq off the axis, so date-valued axis operations must keep working
s = pd.Series(
np.arange(5.0), index=date_range("2020-01-01", periods=5, freq="D")
)
ax = s.plot(kind="bar")
ax.set_xlim("2020-01-01", "2020-01-05")
ax.axvline(s.index[2])
assert ax.get_xlim() == (
Period("2020-01-01", freq="D").ordinal,
Period("2020-01-05", freq="D").ordinal,
)
@pytest.mark.parametrize("xlim", [None, ("2020-01-01", "2020-01-02")])
def test_bar_plot_date_axis_rot_applies_to_minor_ticks(self, xlim):
# GH#1918 - the minor ticks carry most of the date labels; with a
# narrow xlim they are only created once _post_plot_logic widens the view
s = pd.Series(
np.arange(10.0), index=date_range("2020-01-01", periods=10, freq="D")
)
ax = s.plot(kind="bar", rot=45, fontsize=16, xlim=xlim)
ax.get_figure().canvas.draw()
labels = ax.get_xticklabels() + ax.get_xticklabels(minor=True)
drawn = [t for t in labels if t.get_text()]
assert drawn
assert {t.get_rotation() for t in drawn} == {45.0}
assert {t.get_fontsize() for t in drawn} == {16.0}
@pytest.mark.parametrize("freq", ["D", "3h"])
def test_bar_plot_date_axis_subplots_sharex(self, freq):
# GH#1918 - as for line plots, only the bottom subplot gets date labels
idx = date_range("2020-01-01", periods=10, freq=freq)
df = pd.DataFrame({"a": np.arange(10.0), "b": np.arange(10.0)}, index=idx)
axes = df.plot(kind="bar", subplots=True)
axes[0].get_figure().canvas.draw()
def drawn(ax):
labels = ax.get_xticklabels() + ax.get_xticklabels(minor=True)
return [t.get_text() for t in labels if t.get_visible() and t.get_text()]
assert drawn(axes[0]) == []
assert drawn(axes[1])
def test_bar_plot_datetime_xticks(self):
# GH#1918 - the converter has to be registered before the user's ticks
# are applied, both so they land on the right ordinals and so it does
# not replace matplotlib's date converter, which warns
idx = date_range("2020-01-01", periods=10, freq="D")
df = pd.DataFrame({"A": np.arange(10.0)}, index=idx)
with tm.assert_produces_warning(None):
ax = df.plot(kind="bar", xticks=[idx[0], idx[5]])
ax.get_figure().canvas.draw()
assert list(ax.get_xticks()) == [
Period("2020-01-01", freq="D").ordinal,
Period("2020-01-06", freq="D").ordinal,
]
def test_bar_plot_does_not_clobber_existing_axis_freq(self):
# GH#1918 - the axes was already decorated by a line plot; overwriting
# the axis freq would resolve later date-valued calls at a scale that
# does not match the line already drawn there
_, ax = plt.subplots()
pd.Series(
np.arange(100.0), index=date_range("2020-01-01", periods=100, freq="D")
).plot(ax=ax)
before = ax.xaxis.convert_units(pd.Timestamp("2020-01-06"))
pd.Series(
np.arange(10.0), index=date_range("2020-01-05", periods=10, freq="W")
).plot(kind="bar", ax=ax)
assert ax.xaxis.convert_units(pd.Timestamp("2020-01-06")) == before
def test_bar_plot_empty_xticks(self):
# GH#1918 - an empty xticks list still goes through the converter
s = pd.Series(
np.arange(5.0), index=date_range("2020-01-01", periods=5, freq="D")
)
ax = s.plot(kind="bar", xticks=[])
assert list(ax.get_xticks()) == []
@pytest.mark.parametrize("freq, dynamic", [("ns", False), ("us", True)])
def test_bar_plot_ordinals_beyond_float64_precision(self, freq, dynamic):
# GH#1918 - matplotlib holds axis coordinates as float64, so ordinals
# past 2**53 (nanoseconds) cannot carry the half-unit bar padding: the
# limits collapse and the dynamic locator would walk ~1e17 periods.
# Those fall back to fixed ticks instead.
s = pd.Series(
np.arange(10.0), index=date_range("2020-01-01", periods=10, freq=freq)
)
if dynamic:
ax = s.plot(kind="bar")
else:
# the ordinals also collapse the fixed-tick path's axis limits;
# matplotlib warns about that on main too, so it is not new here
msg = "Attempting to set identical low and high xlims"
with tm.assert_produces_warning(
UserWarning, match=msg, check_stacklevel=False
):
ax = s.plot(kind="bar")
assert (
isinstance(
ax.get_xaxis().get_major_formatter(), conv.TimeSeries_DateFormatter
)
is dynamic
)
# must not blow up while locating ticks
ax.get_figure().canvas.draw()
@pytest.mark.parametrize(
"bar_freq, line_freq", [("W", "D"), ("ME", "D"), ("D", "h")]
)
def test_bar_plot_then_line_plot_at_other_freq(self, bar_freq, line_freq):
# GH#1918 - a bar plot must not register the axes as a resamplable
# time-series axes: maybe_resample() would then try to resample it for
# the line, and _replot_ax()'s ax.clear() would erase the bars. Only
# that survival is asserted here; bars and lines at different freqs sit
# on different ordinal scales, which is a separate pre-existing issue
_, ax = plt.subplots()
pd.Series(
np.arange(20.0), index=date_range("2020-01-05", periods=20, freq=bar_freq)
).plot(kind="bar", ax=ax)
assert len(ax.patches) == 20
pd.Series(
np.arange(100.0),
index=date_range("2020-01-05", periods=100, freq=line_freq),
).plot(ax=ax)
assert len(ax.patches) == 20
assert len(ax.get_lines()) == 1
def test_barh_plot_datetime_index_not_date_formatted(self):
# GH#1918 - for barh the x-axis is the value axis; the date formatter
# must not be applied to it
df = pd.DataFrame(
{"A": [1.5, 2.5, 3.5]}, index=date_range("2020-01-01", periods=3)
)
ax = df.plot(kind="barh")
ax.get_figure().canvas.draw()
assert not isinstance(
ax.get_xaxis().get_major_formatter(), conv.TimeSeries_DateFormatter
)
y_labels = [t.get_text() for t in ax.get_yticklabels()]
assert y_labels == [
"2020-01-01 00:00:00",
"2020-01-02 00:00:00",
"2020-01-03 00:00:00",
]
def test_bar_plot_datetime_index_inferred_freq(self):
# GH#66771 - the index freq attribute is unset but inferable, so the
# bar plot must resolve the freq instead of raising AttributeError
idx = DatetimeIndex(["2020-01-01", "2020-01-02", "2020-01-03"])
assert idx.freq is None
df = pd.DataFrame({"A": [1, 2, 3]}, index=idx)
ax = df.plot(kind="bar")
assert isinstance(
ax.get_xaxis().get_major_formatter(), conv.TimeSeries_DateFormatter
)
def test_barh_plot_datetime_index_inferred_freq(self):
# GH#66771 - barh shares the freq-resolution path with bar but keeps
# the string tick labels, since for barh the index is on the y-axis
idx = DatetimeIndex(["2020-01-01", "2020-01-02", "2020-01-03"])
assert idx.freq is None
df = pd.DataFrame({"A": [1, 2, 3]}, index=idx)
ax = df.plot(kind="barh")
ax.get_figure().canvas.draw()
y_labels = [t.get_text() for t in ax.get_yticklabels()]
assert y_labels == [
"2020-01-01 00:00:00",
"2020-01-02 00:00:00",
"2020-01-03 00:00:00",
]
@pytest.mark.parametrize("kind", ["bar", "barh"])
def test_bar_plot_datetime_index_freq_from_axes(self, kind):
# GH#66771 - the index carries no freq of its own, but the axes was
# already decorated by a line plot; that freq is stored as a period
# alias string, so it has to be normalized to an offset before it
# reaches the converter
_, ax = plt.subplots()
pd.Series(
np.arange(10.0), index=date_range("2020-01-01", periods=10, freq="D")
).plot(ax=ax)
idx = DatetimeIndex(["2020-01-02", "2020-01-05"])
assert idx.freq is None
assert idx.inferred_freq is None
pd.Series([1.0, 2.0], index=idx).plot(kind=kind, ax=ax)
# the bars are centered on the same daily ordinals as the line
if kind == "bar":
centers = [p.get_x() + p.get_width() / 2 for p in ax.patches]
else:
centers = [p.get_y() + p.get_height() / 2 for p in ax.patches]
assert centers == [
Period("2020-01-02", freq="D").ordinal,
Period("2020-01-05", freq="D").ordinal,
]
def _check_plot_works(f, freq=None, series=None, *args, **kwargs):
fig = plt.gcf()
fig.clf()
ax = fig.add_subplot(211)
orig_ax = kwargs.pop("ax", plt.gca())
orig_axfreq = getattr(orig_ax, "freq", None)
ret = f(*args, **kwargs)
assert ret is not None # do something more intelligent
ax = kwargs.pop("ax", plt.gca())
if series is not None:
dfreq = series.index.freq
if isinstance(dfreq, BaseOffset):
dfreq = dfreq.freqstr
if orig_axfreq is None:
assert ax.freq == dfreq
if freq is not None and orig_axfreq is None:
assert to_offset(ax.freq, is_period=True) == freq
ax = fig.add_subplot(212)
kwargs["ax"] = ax
ret = f(*args, **kwargs)
assert ret is not None # TODO: do something more intelligent