How to plot day and month

纵饮孤独 提交于 2021-02-19 05:14:05

问题


I have a chart of a daily trend over time.

Price 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:

Final Price chart


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!