我有 python 函数,可以创建 6 个月数据系列的图表。 一个函数的示例:
def result(data):
fig = plt.figure(figsize=(12, 8), dpi=150)
ax = plt.subplot(111)
data = data.sort_values(by='period', ascending=1)
box = ax.get_position()
ax.spines['top'].set_visible(True)
ax.spines['right'].set_visible(True)
plt.plot(data['period'], data['result'], label='Result', solid_capstyle='round', marker='o', color='#92c6ff')
plt.plot(data['period'], data['peer_result'], label='Peer Result', color='#5990C6', linestyle='--')
annotate_chart(data['period'], data['result'].round(1))
plt.legend(loc='upper center', fontsize=20, bbox_to_anchor=(0.5, -0.15), frameon=False, ncol=4)
plt.ylabel('(%)', fontsize=28, weight='bold')
plt.xticks(data['period'], data['month'], rotation=45, fontsize=28)
plt.yticks(fontsize=28)
plt.title('Results', fontsize=28)
plt.tight_layout()
img = files_loc + '/result.png'
plt.savefig(img)
plt.close(fig)
# Line fill graph placement
pdf.set_xy(4, 30)
pdf.image(img, w=105, h=75)
数据集的格式为:
期 | 月 | 结果 | 同行结果 |
---|---|---|---|
202308 | 八月 | 82.14 | 83.22 |
202309 | 九月 | 81.47 | 82.37 |
202310 | 十月 | 82.87 | 82.53 |
202311 | 十一月 | 84.68 | 83.52 |
202312 | 十二月 | 83.26 | 82.58 |
202401 | 一月 | 83.28 | 82.78 |
当我调用完整数据集的函数(包括 2024 年 1 月)时,图表包含 2023 年的压缩数据:
result(data)
...但是当我仅使用 2023 年数据时,图表看起来不错:
result(data.head(5))
当我尝试调用
result(data.tail(5))
时,问题再次出现,因此它与数据集的大小无关。
我尝试将 data['period'] 转换为数值和分类值 - 它不起作用。
这里可能存在什么问题?
我尝试将数据['period'] 转换为数值和分类值 - 它不起作用。 我希望该图表能够呈现完整的数据(包括 2024 年),无需修改。
您的
"period"
数据仅被视为整数。您可以将其将其转换为datetime
对象(假设您的data
是熊猫DataFrame
)。一个简单的例子是:
from matplotlib import pyplot as plt
import pandas as pd
data = pd.DataFrame(
{
"period": [202308, 202309, 202310, 202311, 202312, 202401],
"result": [82, 81, 82, 85, 83, 83],
"month": ["AUG", "SEP", "OCT", "NOV", "DEC", "JAN"]
}
)
# convert period to datetime format
data["period"] = pd.to_datetime(data["period"], format="%Y%m")
fig, ax = plt.subplots()
ax.plot(data["period"], data["result"])
ax.set_xticks(data['period'], data['month'], rotation=45, fontsize=14)