Python matplotlib:如何向标记标签添加逗号?
我有以下数据帧:Python matplotlib:如何向标记标签添加逗号?,python,matplotlib,Python,Matplotlib,我有以下数据帧: df_test = pd.DataFrame( [[2006, 371934], [2007, 403230], [2008, 401525], [2009, 421313], [2010, 422322], [2011, 412859], [2012, 396279], [2013, 393809], [2014, 387727], [2015, 339470], [2016, 314864], [2017, 286225], [2018, 24677
df_test = pd.DataFrame(
[[2006, 371934],
[2007, 403230],
[2008, 401525],
[2009, 421313],
[2010, 422322],
[2011, 412859],
[2012, 396279],
[2013, 393809],
[2014, 387727],
[2015, 339470],
[2016, 314864],
[2017, 286225],
[2018, 246773],
[2019, 214617]],
columns=['year', 'arrests']
)
我使用matplotlib创建了以下绘图:
fig, ax = plt.subplots()
ax.plot(df_test.year, df_test.arrests, marker='o')
ax.set_xlabel("Year")
ax.set_ylabel("Number of Arrests")
ax.set_title("Arrests by Year")
plt.xticks([x for x in df_test.year])
plt.xticks(rotation = 90)
for i,j in zip(df_test.year, df_test.arrests):
ax.annotate(j, xy=(i,j))
ax.yaxis.set_major_formatter(
ticker.FuncFormatter(lambda y, p: format(int(y), ','))
)
plt.show()
如何向标记标签添加逗号
我该如何分离标记标签,使其不重叠?您可以在annotate中使用相同的功能
格式。对于注释的分离,一种简单的方法是增加绘图的大小:
将matplotlib.ticker导入为ticker
# increase the size here
fig, ax = plt.subplots(figsize=(12,9))
ax.plot(df_test.year, df_test.arrests, marker='o')
ax.set_xlabel("Year")
ax.set_ylabel("Number of Arrests")
ax.set_title("Arrests by Year")
plt.xticks([x for x in df_test.year])
plt.xticks(rotation = 90)
for i,j in zip(df_test.year, df_test.arrests):
# format to add `,` here
ax.annotate(format(int(j), ','), xy=(i,j))
ax.yaxis.set_major_formatter(
ticker.FuncFormatter(lambda y, p: format(int(y), ','))
)
输出:
当我使用ax.figure.savefig()保存绘图时,结果是这样的:是否应用了其他格式?