matplotlib 子图中的乱码 x 轴标签
Garbled x-axis labels in matplotlib subplots
我正在查询 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();
建议:
- 增加图形的高度。
fig, axes = plt.subplots(14, 4, figsize = (12,20), sharex = True)
- 旋转所有标签:
fig.autofmt_xdate(rotation=90)
- 在末尾使用
tight_layout
而不是 subplots_adjust
:
fig.tight_layout()
我正在查询 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();
建议:
- 增加图形的高度。
fig, axes = plt.subplots(14, 4, figsize = (12,20), sharex = True)
- 旋转所有标签:
fig.autofmt_xdate(rotation=90)
- 在末尾使用
tight_layout
而不是subplots_adjust
:fig.tight_layout()