python - 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();
解决方案
推荐阅读
- java - 创建公告板时,我在问如何设置 id 和 post number 主键
- swiftui - SwiftUI 的 List/ForEach 视图中是否可以有一个 Button(action: -)
- python - Streamlit 中的登录页面问题
- java - 从键盘读取并忽略打印的文本
- javascript - 如何使用 Javascript 监听值变化的特定键?
- javascript - 通过计算字符长度将 JS 数组拆分和连接成块
- javascript - 广告未呈现
- json - Jq 在使用 AWS Secrets Manager 解析时添加额外的双引号
- c# - ServiceStack.Redis:所有 MQ 请求处理程序的一个线程池?
- python - 列表理解以删除不需要的对象。验证它按预期工作