简体   繁体   English

如何减少在matplotlib图上显示的xticks数量?

[英]How can I reduce the number of xticks displayed on a matplotlib plot?

I'm plotting time series data and I would like to maintain the resolution in the curves, but I want to display fewer years on the x-axis. 我正在绘制时间序列数据,并且希望保持曲线的分辨率,但是我想在x轴上显示更少的年份。 I've parsed the 'Year' column as dates and I've made that column into the dataframe's index. 我已将“年份”列解析为日期,并将该列放入数据框的索引中。 I feel like it should be easy to thin down the frequency of the labels, but everything I've tried has simply made the labels inaccurate. 我觉得应该很容易地降低标签的频率,但是我尝试过的所有事情都只是使标签不准确。

The DataFrame has the form: DataFrame具有以下形式:

print(total_df.head())

         All ages  Age 18 or older
Year                           
1978     131.0            183.0
1979     133.0            185.0
1980     138.0            191.0
1981     153.0            211.0
1982     170.0            232.0

And I've been using this code to produce my plot. 而且我一直在使用此代码来制作我的情节。

with sns.axes_style("whitegrid"):
    fig, ax = plt.subplots(figsize=(10,7))
    ax.plot(total_df['All ages'])
    ax.plot(total_df['Age 18 or older'])
    ax.set_title('Total Imprisonment Rates (table: p16f01)')
    ax.set_xlabel('Year')
    ax.set_ylabel('People imprisoned (per 100k US population)')
    ax.set_xticklabels(total_df.index, rotation=70)
    ax.legend()
    ax.set_ylim([0, 1.1*max([total_df['All ages'].max(), 
                             total_df['Age 18 or older'].max()])])

Which produces 哪个产生 总监禁情节

This shouldn't happen. 这不应该发生。 And it wouldn't happen if you made sure your index are actual numbers, not strings. 如果您确定索引是实际数字而不是字符串,则不会发生。

To convert your index to numbers, use eg 要将索引转换为数字,请使用例如

df.index = df.index.values.astype(int)

Then remove the set_xticklabels line, because this would anyway only make sense if you set the ticks via set_ticks as well. 然后删除set_xticklabels行,因为这同样只有在您也通过set_ticks设置刻度set_ticks This will then assure that matplotlib automatically chooses useful spacings between the ticks. 然后,这将确保matplotlib自动在刻度之间选择有用的间距。

Complete example: 完整的例子:

import matplotlib.pyplot as plt
import numpy as np;np.random.seed(9)
import pandas as pd

inx = np.arange(1978,2017).astype(str)
a = np.cumsum(np.random.randn(len(inx),2), axis=0)+10
df = pd.DataFrame(a, index=inx, columns=list("AB"))

df.index = df.index.values.astype(int)

fig, ax = plt.subplots(figsize=(10,7))
ax.plot(df['A'])
ax.plot(df['B'])

ax.set_xlabel('YEAR')

ax.legend()
ax.set_ylim([0, 1.1*max([df['A'].max(), 
                         df['B'].max()])])

plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM