编辑 x 轴刻度标签的日期格式
- 2025-01-10 08:46:00
- admin 原创
- 123
问题描述:
我想编辑 x 轴上日期的格式。下图显示了它们默认出现在我的条形图上的方式。我想删除“Dec”和“2012”的重复,只保留 x 轴上的实际日期数字。
关于我该如何做到这一点,有什么建议吗?
解决方案 1:
简而言之:
import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)
matplotlib 网站上有很多示例。我最常用的是这里
解决方案 2:
虽然Paul H 给出的答案展示了关键部分,但它不是一个完整的示例。另一方面,matplotlib 示例似乎相当复杂,并且没有展示如何使用天数。
因此,对于有需要的每个人来说,这里有一个完整的工作示例:
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)
myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)
## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()
解决方案 3:
如本例所示,从包matplotlib.dates中,日期格式可应用于轴标签和绘图刻度。
下面我给出了一个为多图标记轴刻度的示例
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
df = pd.read_csv('US_temp.csv')
plt.plot(df['Date'],df_f['MINT'],label='Min Temp.')
plt.plot(df['Date'],df_f['MAXT'],label='Max Temp.')
plt.legend()
####### Use the below functions #######
dtFmt = mdates.DateFormatter('%b') # define the formatting
plt.gca().xaxis.set_major_formatter(dtFmt) # apply the format to the desired axis
plt.show()
就这么简单
解决方案 4:
这对我来说非常有效
import matplotlib.pyplot as plt
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator)
import matplotlib.dates as mdates
dtFmt = mdates.DateFormatter('%Y-%b') # define the formatting
plt.gca().xaxis.set_major_formatter(dtFmt)
# show every 12th tick on x axes
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=1))
plt.xticks(rotation=90, fontweight='light', fontsize='x-small',)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD