I have a pandas dataframe data
like this;
num
Date
2020-03-01 311
2020-03-08 432
2020-03-15 420
2020-03-22 304
2020-03-29 1030
2020-04-05 1497
2020-04-12 2259
2020-04-19 1938
Where Date
is DatetimeIndex
. I tried to plot it as below;
from matplotlib import pyplot as plt
x = data.index
fig = plt.figure()
ax1 = fig.add_subplot(111)
tested_plot = ax1.bar(x, data["num"])
dates_fmt = mdates.DateFormatter('%m/%d')
ax1.xaxis.set_major_formatter(dates_fmt)
plt.show()
I wanted the ticks in xaxis to be shown on where the bar exists (like 3/1, 3/8,..., 4/12, 4/19). But when I plot the above, the ticks are reset when April begins and the bars and the ticks are not corresponding;
I know I can convert DatetimeIndex
to Index
of string using strftime
which will solve the problem, but I would like to keep DatetimeIndex
for further customization. I also used
import matplotlib.dates as mdates
ax1.xaxis.set_major_locator(mdates.DayLocator(interval=7))
to force ticks to be a week apart, but then I cannot set the start date for ticks and now no bars are on the ticks. Does anybody know how to fix this?
You can try pandas.DataFrame.plot
and matplotlib.axes.Axes.set_xticklabels
. In the set_xticklabels
method, you can format dates as you want (here using pandas.Series.dt.strftime
):
df.plot(kind="bar", ax=ax1)
ax1.set_xticklabels([date.strftime("%Y-%m-%d") for date in df.index],
rotation=45)
Full code
# Be sure dates are datetime objects
# df["Date"] = pd.to_datetime(df["Date"])
# df.set_index("Date", inplace=True)
print(df)
# num
# Date
# 2020-03-01 311
# 2020-03-08 432
# 2020-03-15 420
# 2020-03-22 304
# 2020-03-29 1030
# 2020-04-05 1497
# 2020-04-12 2259
# 2020-04-19 1938
fig = plt.figure()
ax1 = fig.add_subplot(111)
df.plot(kind="bar", ax=ax1)
ax1.set_xticklabels([date.strftime("%Y-%m-%d") for date in df.index],
rotation=45)
plt.show()
output
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.