python - 在上部子图上显示 xtick 标签

标签 python matplotlib datetime plot visualization

我觉得我已经尝试了我能在这里找到的所有东西,谷歌、matplotlib 文档和其他几个论坛。我无法让 xticks 显示在上部子图/图表和下部子图/图表上。我在与 matplotlib 相关的论坛中读到,其他人也有与我相同的问题,使用早期版本的 matplotlib,但该线程几年前就死了,而建议起作用的修复程序在我的情况下却不起作用。

数据从 CSV 文件中提取,并转换为 float 和日期时间值

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
import numpy as np

y = [26.0, 24.6, 23.9, 23.7, 23.6, 21.8, 22.0, 23.6]
x = [datetime.datetime(2020, 9, 2, 14, 13), datetime.datetime(2020, 9, 2, 14, 23), datetime.datetime(2020, 9, 2, 14, 33), datetime.datetime(2020, 9, 2, 14, 43), datetime.datetime(2020, 9, 2, 14, 53), datetime.datetime(2020, 9, 3, 0, 3), datetime.datetime(2020, 9, 4, 0, 3), datetime.datetime(2020, 9, 4, 0, 13)]
out = {datetime.date(2020, 9, 2): [26.0, 24.6, 23.9, 23.7, 23.6], datetime.date(2020, 9, 3): [21.8], datetime.date(2020, 9, 4): [21.6, 21.6]}

'''I found a thread a couple of days ago, where these 2 lines were the fix. honestly don't remember what the problem was, except it was related to datetime and plt'''
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y %H:%M'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())

ax1 = plt.subplot(2, 1, 1)
plt.plot(x, y)
plt.xlabel('time')
plt.ylabel('temp')
plt.title('logs')
plt.grid()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y %H:%M'))

'''and also found how to subplot a boxplot from dict, from another thread'''
ax2 = plt.subplot(2, 1, 2)
labels, data = [*zip(*out.items())]  # 'transpose' items to parallel key, value lists
plt.boxplot(data)
plt.xticks(range(1, len(labels) + 1), labels)
plt.xlabel('date')
plt.ylabel('temp')

'''for rotating the xticklabels, and as far as I've been able to read, the most likely culprit'''
plt.gcf().autofmt_xdate()

plt.draw() # non-blocking call

plt.show() # keep last in script to keep windows open after execution

This is the result

它可能只是 plt.gcf().autofmt_xdate() 如果是的话,有没有办法显示两个子图的 xticklabels,并且仍然让它们旋转?

最佳答案

这是一个使用 Matplotilb 面向对象界面的解决方案,可让您对齐轴并旋转轴上的标签。在子图中共享 x 轴使得缩放适用于两个子图。

上面的子图上的刻度线通过使用打开

up.tick_params(labelbottom=True)

使用 matplotlib 的日期值定位箱线图,该日期值对应于使用的日期时间

mdates.date2num(d)
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
import numpy as np
import datetime


y = [26.0, 24.6, 23.9, 23.7, 23.6, 21.8, 22.0, 23.6]
x = [datetime.datetime(2020, 9, 2, 14, 13), datetime.datetime(2020, 9, 2, 14, 23), datetime.datetime(2020, 9, 2, 14, 33), datetime.datetime(2020, 9, 2, 14, 43), datetime.datetime(2020, 9, 2, 14, 53), datetime.datetime(2020, 9, 3, 0, 3), datetime.datetime(2020, 9, 4, 0, 3), datetime.datetime(2020, 9, 4, 0, 13)]
out = {datetime.date(2020, 9, 2): [26.0, 24.6, 23.9, 23.7, 23.6], datetime.date(2020, 9, 3): [21.8], datetime.date(2020, 9, 4): [21.6, 21.6]}


f, (up, down) = plt.subplots(2, 1, sharex=True)

up.plot(x, y)
up.set_xlabel('time')
up.set_ylabel('temp')
up.set_title('logs')
up.grid()

down.boxplot(
    out.values(),
    positions=[mdates.date2num(d) for d in out.keys()]
)

down.get_xaxis().set_major_formatter(mdates.DateFormatter('%d-%m-%Y %H:%M'))
down.get_xaxis().set_major_locator(mdates.DayLocator())

up.tick_params(labelbottom=True)

plt.setp( up.xaxis.get_majorticklabels(), rotation=30 )
plt.setp( down.xaxis.get_majorticklabels(), rotation=30 )

f.tight_layout()
plt.draw()

请注意autofmt_xdate显式关闭除底部子图之外的所有子图的刻度标签。

Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared x-axis where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels.

这个答案与 @Zephyr 的答案类似,但我无论如何都会发布它,因为它正确地对齐了图之间的数据。您可以通过在下部图上设置一天中的不同时间或更改框的宽度来更改对齐方式。

The result

关于python - 在上部子图上显示 xtick 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68802263/

相关文章:

python pandas 解析带有月份名称的日期时间字符串

python - 使用 ephem 计算 "Solar Noon",转换为本地时间

python - 你如何在 python 中的 plotly 框中设置框宽度?

python - 从电子邮件文本中解析 "From"地址

python-3.x - 如何将计数添加到直方图?

c# - 将字符串转换为有效的日期时间

python - 类型错误 : 'list' object is not callable when web scraping to append lists/values to a column in csv file

python - Matplotlib 散点图和颜色图的问题

Python,为什么 i=+1 不会导致无限循环?

datetime - 在 GWT 中获取日期详细信息(日、月、年)