gpt4 book ai didi

python - 减少 x 轴上标签为日期的刻度数

转载 作者:行者123 更新时间:2023-12-01 08:32:13 24 4
gpt4 key购买 nike

我是 matplotlib 新手,正在使用 matplotlib.plot 创建图表,x 轴用日期标记,Y 轴用数字标记

x = ['2018-08-17', '2018-08-20', '2018-08-21', '2018-08-22', '2018-08-23', '2018-08-24', '2018-08-27', '2018-08-28', '2018-08-29', '2018-08-30', '2018-08-31','2018-11-29', '2018-11-30', '2018-12-03', '2018-12-04', '2018-12-05']

y = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

我使用下面的代码将这些字符串日期转换为实际日期

xdates = [dt.strptime(dstr,'%Y-%m-%d').date() for dstr in x]

将其转换为日期后,我尝试了

plt.xticks(range(0,len(xdates),2),xdates[1::2],rotation=50)

plt.plot(xdates,y)

但它什么也没做。

我想在 x 轴上放置更少的刻度和标签。假设有 15 个日期,但我只想在 x 轴上显示 7 或 8 个日期。我怎样才能实现这个目标?

以下是创建趋势图的方法

def _create_trend_graph(self,element):
if(len(self.processed_data)!=0):

x_axis = element['X-Axis']
y_axis = []
plt.xticks(rotation=70)
plt.yticks(np.arange(0, 10001,element['Range']))
#plt.yticks(np.arange(0, 101,10))
figure = plt.gcf() # get current figure
figure.set_size_inches(14, 8)
for key in element.iterkeys():
if key.lower().startswith("y-axis"):
self.null_index = len(self.processed_data[element[key]])
for index in range(len(self.processed_data[element[key]])):
if self.processed_data[element[key]][index] == 'Null':
self.null_index = index
break
plt.plot(self.processed_data[x_axis][:self.null_index], list(map(float, self.processed_data[element[key]][:self.null_index])))
y_axis = y_axis + [str(element[key])]
#plt.legend(y_axis, prop={'size': 16})
plt.legend(y_axis)
plt.rcParams['font.size'] = 10.0
plt.savefig(self.monitored_folder+element['Title'], bbox_inches='tight', dpi = 100)
plt.close()
self._add_image_to_body(str(element['Title']), str(element['height']), str(element['width']))
else:
self._create_NA()

这里元素['X-Axis']我们有日期,例如,

['2018-08-17', '2018-08-20', '2018-08-21', '2018-08-22', '2018-08-23', '2018-08-24 ', '2018-08-27', '2018-08-28', '2018-08-29', '2018-08-30', '2018-08-31', '2018-11-29', '2018-11-30', '2018-12-03', '2018-12-04', '2018-12-05']

在 y 轴上我们输入数字。所以问题实际上是我们在 element['X-Axis'] 中获取了大量日期,因此它只会使 xaxis 变得非常拥挤。 future 日期的数量也可能会增加。

一种解决方案是仅增加图表的大小,但这是我们最不想做的事情。由于我没有太多声誉,因此无法附加图片。我还能如何向您展示图像@ImportanceofbeingErnest

生成图表后,我们将其传递给下面的方法

def _add_image_to_body(self,image_name,height,width):
attachment = self.mail.Attachments.Add(self.monitored_folder+image_name+'.png')
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", image_name.replace(' ','_'))
self.html += ("<img src=\"cid:" + image_name.replace(' ', '_') + '\"' + " height="+height+" width="+width+"><br><br>")

最佳答案

我认为您遇到的问题是 matplotlib 的 AutoDateLocator 目前每隔一个月的 29 号进行一次标记,因此它的标签将与下个月的第一天重叠。

import matplotlib.pyplot as plt
from datetime import datetime as dt

x = ['2018-08-17', '2018-08-20', '2018-08-21', '2018-08-22', '2018-08-23', '2018-08-24',
'2018-08-27', '2018-08-28', '2018-08-29', '2018-08-30', '2018-08-31','2018-11-29',
'2018-11-30', '2018-12-03', '2018-12-04', '2018-12-05']
y = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

xdates = [dt.strptime(dstr,'%Y-%m-%d') for dstr in x]

plt.plot(xdates,y)

plt.setp(plt.gca().get_xticklabels(), rotation=60, ha="right")
plt.tight_layout()
plt.show()

enter image description here

这可以被视为一个错误。但它在当前的开发版本中得到了修复,从 matplotlib 3.1 开始,这个问题应该不会再出现了。

解决方法是自己定义一个代码,在每个月的第一天和第 15 号进行标记。

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime as dt

x = ['2018-08-17', '2018-08-20', '2018-08-21', '2018-08-22', '2018-08-23', '2018-08-24',
'2018-08-27', '2018-08-28', '2018-08-29', '2018-08-30', '2018-08-31','2018-11-29',
'2018-11-30', '2018-12-03', '2018-12-04', '2018-12-05']
y = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

xdates = [dt.strptime(dstr,'%Y-%m-%d') for dstr in x]

plt.plot(xdates,y)

plt.gca().xaxis.set_major_locator(mdates.DayLocator((1,15)))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
plt.setp(plt.gca().get_xticklabels(), rotation=60, ha="right")
plt.tight_layout()
plt.show()

enter image description here

关于python - 减少 x 轴上标签为日期的刻度数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53863600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com