以下这个问题我想更改X范围(日期),以便从1970年、1980年……到2020年,事件将是a..b等……(我有预定义的事件列表)。我使用以下代码,日期从 1969 年开始,到 1970 年结束(而不是分别是 1970 年和 2020 年)。尝试过的2个选项: '事件': ['a', 'b', 'c', 'd', 'e', 'f'], 第一个选项:
'date':pd.date_range(start='1970', periods=6)
第二个选项:
'date': ['1970', '1980','1990','2000','2010','2020']
完整代码如下:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
from datetime import datetime
df = pd.DataFrame(
{
'event': ['a', 'b','c','d','e','f'],
'date': ['1970','1980','1990','2000','2010','2020']
# -> 'date':pd.date_range(start='1970', periods=6)
}
)
df['date'] = pd.to_datetime(df['date'])
levels = np.tile(
[-5, 5, -3, 3, -1, 1],
int(np.ceil(len(df)/6))
)[:len(df)]
fig, ax = plt.subplots(figsize=(12.8, 4), constrained_layout=True);
ax.set(title="A series of events")
ax.vlines(df['date'], 0, levels, color="tab:red"); # The vertical stems.
ax.plot( # Baseline and markers on it.
df['date'],
np.zeros_like(df['date']),
"-o",
color="k",
markerfacecolor="w"
);
# annotate lines
for d, l, r in zip(df['date'], levels, df['event']):
ax.annotate(
r,
xy=(d, l),
xytext=(-3, np.sign(l)*3),
textcoords="offset points",
horizontalalignment="right",
verticalalignment="bottom" if l > 0 else "top"
);
# format xaxis with 4 month intervals
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=4));
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"));
plt.setp(ax.get_xticklabels(), rotation=30, ha="right");
# remove y axis and spines
ax.yaxis.set_visible(False);
ax.yaxis.set_visible(False);
ax.spines["left"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.margins(y=0.1);
plt.show();
如上所述,我只想在 Xais 上看到 1970 年至 2020 年(没有月份和日期)以及它们各自的事件(a 到 f)。
根据评论和我的理解回答,请参阅下面的完整代码(请注意,我刚刚为
year
添加了一行,并注释掉了 xaxis
部分):
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
from datetime import datetime
import pandas as pd
df = pd.DataFrame(
{
'event': ['a', 'b','c','d','e','f'],
'date': ['1970','1980','1990','2000','2010','2020']
# -> 'date':pd.date_range(start='1970', periods=6)
}
)
df['date'] = pd.to_datetime(df['date'])
df['date'] = df['date'].dt.year # ADDED THIS!
levels = np.tile(
[-5, 5, -3, 3, -1, 1],
int(np.ceil(len(df)/6))
)[:len(df)]
fig, ax = plt.subplots(figsize=(12.8, 4), constrained_layout=True);
ax.set(title="A series of events")
ax.vlines(df['date'], 0, levels, color="tab:red"); # The vertical stems.
ax.plot( # Baseline and markers on it.
df['date'],
np.zeros_like(df['date']),
"-o",
color="k",
markerfacecolor="w"
);
# annotate lines
for d, l, r in zip(df['date'], levels, df['event']):
ax.annotate(
r,
xy=(d, l),
xytext=(-3, np.sign(l)*3),
textcoords="offset points",
horizontalalignment="right",
verticalalignment="bottom" if l > 0 else "top"
);
# COMMENTED OUT THIS!
# format xaxis with 4 month intervals
# ax.xaxis.set_major_locator(mdates.MonthLocator(interval=4));
# ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"));
plt.setp(ax.get_xticklabels(), rotation=30, ha="right");
# remove y axis and spines
ax.yaxis.set_visible(False);
ax.yaxis.set_visible(False);
ax.spines["left"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.margins(y=0.1);
plt.show();