如何解决Python 区域图:自定义日期 x-tick 位置和标签,以及设置的 x-limit
我必须遵循以下代码:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Area Plot
plt.figure(figsize=(15,5))
x=pd.date_range('1992-1-1','2014-12-31',freq='6MS').strftime("%Y-%m").tolist()
y=np.random.uniform(-3,3,len(x))
plt.fill_between(x[1:],y[1:],where=y[1:] >= 0,facecolor='red',interpolate=True,alpha=0.7,label='Up')
plt.fill_between(x[1:],where=y[1:] <= 0,facecolor='green',label='Down')
plt.show
#plt.savefig('file')
这使得下图 但是,x 标签太多且拥挤。当我设置 x 限制时
plt.xlim(["1990-01","2015-1"])
plt.xticks(["1990","1995","2000","2005","2010","2015"])
(1) 如何每年或五年显示x-labels?
(2) 如何每 6 个月或每年显示一次 x-ticks?
(3) 如何设置1993年到2015年的xlim?
解决方法
处理此问题的一种方法是将 xticklabels
旋转
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Area Plot
plt.figure(figsize=(15,5))
x=pd.date_range('1992-1-1','2014-12-31',freq='6MS').strftime("%Y-%m").tolist()
y=np.random.uniform(-3,3,len(x))
plt.fill_between(x[1:],y[1:],where=y[1:] >= 0,facecolor='red',interpolate=True,alpha=0.7,label='Up')
plt.fill_between(x[1:],where=y[1:] <= 0,facecolor='green',label='Down')
plt.xticks(x,rotation=90)
plt.show()
然后,如果您愿意,可以使用以下方法使某些 xticks
不可见:
fig = plt.figure(figsize=(15,rotation=90)
for label in fig.axes[0].xaxis.get_ticklabels()[::2]:
label.set_visible(False)
plt.show()
,
此代码有效
import numpy as np
import pandas as pd
from datetime import datetime,date,time
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
x=pd.date_range('1993-01-01',periods=44,freq='2Q',closed='left')
y=np.random.uniform(-3,44)
fig=plt.figure(figsize=(15,5))
ax=fig.add_subplot(1,1,1)
ax.fill_between(x[0:],y[0:],where=y[0:] >= 0,label='Up')
ax.fill_between(x[0:],where=y[0:] <= 0,label='Down')
#[Questions 1 and 2] format the x-ticks and labels
years = mdates.YearLocator() # every 1 year
#years = mdates.YearLocator(5) # every 5 years
months = mdates.MonthLocator(bymonth=[1,7,13]) # every month
years_fmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)
ax.xaxis.set_minor_locator(months)
#[Question 3]x-axis limit
Start=1993
End=2015
start = datetime(year=Start,month=1,day=1,hour=0)
end = datetime(year=End,hour=0)
ax.set_xlim(start,end)
plt.show()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。