问题
I have a chart of a daily trend over time.
The year is not relevant here and I want to show only day and month. I know you can show year and month but that is not the case.
I tried to create a new variable called "Day_Month":
import datetime as dt
df['Day'] = df['date'].dt.day
df['Month'] = df['date'].dt.month
df['Day_Month'] = df['Day'].astype(str) + "-" +
but it's not possible to plot it as a string nor to convert it to date type.
eventually, I would like my chart to look like this:
回答1:
The answer I found is:
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
plt.plot(date, price , label="Price")
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
回答2:
import numpy as np
import matplotlib.pyplot as plt
import datetime
x = [0, 1, 2, 3, 4, 5, 6]
y = [0, 5, 20, 35, 40, 20, 15]
now = datetime.datetime.now()
m = now.month
d = now.day
d1 = str(d) + "-" + str(m)
d2 = d1[:len(d1)-1] + "5"
d3 = d1[:len(d1)-1] + "6"
d4 = d1[:len(d1)-1] + "7"
d5 = d1[:len(d1)-1] + "8"
d6 = d1[:len(d1)-1] + "9"
Day_Month = ["0", d1, d2, d3, d4, d5, d6]
X = np.array(x)
Y = np.array(y)
plt.scatter(X, Y)
plt.plot(y, color='g', linestyle='--', label="--Price")
plt.xlabel("days")
plt.ylabel("Price")
plt.xticks(X, Day_Month)
plt.show()
来源:https://stackoverflow.com/questions/49975878/how-to-plot-day-and-month