首页 > 解决方案 > matplotlib 子图中的乱码 x 轴标签

问题描述

我正在查询 COVID-19 数据并为其中一个数据点(阳性测试结果)构建一个每日变化的数据框,其中每一行是一天,每一列是一个州或地区(总共有 56 个)。然后我可以为每个州生成一个图表,但我无法让我的 x 轴标签(日期)表现得像我想要的那样。我怀疑有两个问题是相关的。首先,标签太多——通常 matplotlib 整齐地减少标签数量以提高可读性,但我认为子图会混淆它。其次,我希望标签垂直阅读;但这只会发生在最后一个情节上。(我尝试移动块rotation='vertical'内部for,但无济于事。)

所有子图的日期都相同,因此——这部分有效——x 轴标签只需要出现在子图的底行。Matplotlib 会自动执行此操作。但我需要更少的标签,并且所有标签都垂直对齐。这是我的代码:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# get current data
all_states = pd.read_json("https://covidtracking.com/api/v1/states/daily.json")
# convert the YYYYMMDD date to a datetime object
all_states[['gooddate']] = all_states[['date']].applymap(lambda s: pd.to_datetime(str(s), format = '%Y%m%d'))

# 'positive' is the cumulative total of COVID-19 test results that are positive 
all_states_new_positives = all_states.pivot_table(index = 'gooddate', columns = 'state', values = 'positive', aggfunc='sum')
all_states_new_positives_diff = all_states_new_positives.diff()

fig, axes = plt.subplots(14, 4, figsize = (12,8), sharex = True )
plt.tight_layout
for i , ax in enumerate(axes.ravel()):
    # get the numbers for the last 28 days
    x = all_states_new_positives_diff.iloc[-28 :].index
    y = all_states_new_positives_diff.iloc[-28 : , i]
    ax.set_title(y.name, loc='left', fontsize=12, fontweight=0)
    ax.plot(x,y)

plt.xticks(rotation='vertical')
plt.subplots_adjust(left=0.5, bottom=1, right=1, top=4, wspace=2, hspace=2)
plt.show();

标签: pythonmatplotlibsubplot

解决方案


建议:

  1. 增加图形的高度。
    fig, axes = plt.subplots(14, 4, figsize = (12,20), sharex = True)
    
  2. 旋转所有标签:
    fig.autofmt_xdate(rotation=90)
    
  3. 最后使用tight_layout而不是subplots_adjust
    fig.tight_layout()
    

在此处输入图像描述


推荐阅读