如何在matplotlib中更改刻度标签的比例?

b1uwtaje  于 2023-01-09  发布在  其他
关注(0)|答案(2)|浏览(177)

我得到了一个问题,不仅修改xticklabel文本,但尝试重新调整它从一天到一个月。
我用Jan-01到Dec-31的数据绘制了一个图,绘制的默认系列是以日期为索引的随机值。
日期01 - 01 - 16.0 01 - 02 - 26.7 01 - 03 - 26.7 01 - 04 - 26.1 01 - 05 - 15.0 ... 12 - 27 - 13.8 12 - 28 - 16.6 12 - 29 - 15.0 12 - 30 - 14.4 12 - 31 - 15.0姓名:数据值,长度:365,数据类型:浮动64
输出看起来很混乱,因为每个xticklabel都在那里,旋转实际上是无用的。我想将它们从天调整到月,最佳实践是什么?我写了一些这样的代码,但我不认为它足够聪明。有什么建议吗?

下面是我的代码:

labels = [item.get_text() for item in ax.get_xticklabels()]
n = 0
for item in labels:
    n=n+1
    if n%15==0 and n%10 !=0:
        labels[n-1]= calendar.month_name[int(labels[n-1].split('-')[0])]
    else:
        labels[n-1]=''

ax.set_xticklabels(labels)
plt.show()

ax.set_xticklabels(labels) plt.show()`
结果如下:

oipij1gg

oipij1gg1#

让我们从必要的导入开始:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdate

我假设源数据是一个pandasonic DataFrame,创建如下:

ind = pd.date_range(start='2021-01-01', end='2021-12-31')
np.random.seed(0)  # To get repatable results
# Upper / lower values
upp = np.random.normal(loc=8, scale=0.5, size=ind.size)
low = np.random.normal(loc=3, scale=0.4, size=ind.size)
# This will be used below
df = pd.DataFrame({'Upper': upp, 'Lower': low}, index = ind)

与:

  • 该索引包含来自一年的连续日期,
    • Lower * 和 * Upper * 列包含两条曲线的值。

生成带有"每月"* x * 轴标签的图的一种可能的解决方案是:

fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(df)
ax.fill_between(df.index, df.Upper, df.Lower, alpha=0.1)
ax.set_ylim(0, 10)
locator = mdate.MonthLocator()
fmt = mdate.DateFormatter('%b')
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(fmt)
plt.show()

结果是:

请注意,您有两个 * Jan * 标签,一个表示年初,另一个表示年末。

rxztt3cl

rxztt3cl2#

我的假设是,你的日期仍然是字符串格式,当你把他们的图形。尝试转换成一个日期时间格式,然后matplot应该做繁重的工作本身从那里。此外,你可以缩放刻度标签与plt.xticks(size = 20)或任何大小,你想要的。例如:

import pandas as pd
import matplotlib.pyplot as plt

dates = ['19 March 2022', '20 March 2022', '21 March 2022', '22 March 2022', 
         '19 April 2022', '20 April 2022', '21 April 2022', '22 April 2022',
         '19 May 2022', '20 May 2022','21 May 2022','22 May 2022',
         '19 June 2022', '20 June 2022','21 June 2022','22 June 2022',
         '19 July 2022', '20 July 2022','21 July 2022','22 July 2022',
         '19 August 2022', '20 August 2022','21 August 2022','22 August 2022',
         '19 September 2022', '20 September 2022','21 September 2022','25 September 2022',
         '19 October 2022', '20 October 2022','21 October 2022','22 October 2022',
         '19 November 2022', '20 November 2022','21 November 2022','22 November 2022',
         '19 December 2022', '20 December 2022', '21 December 2022', '22 December 2022']
values = [1,2,3,4,
          1,2,3,4,
          1,2,3,4,
          1,2,3,4,
          1,2,3,4,
          1,2,3,4,
          1,2,3,4,
          1,2,3,4,
          1,2,3,4,
          1,2,3,4]
df = pd.DataFrame(zip(values, dates), columns = ['values', 'dates'])

plt.plot(df['dates'], df['values'])
plt.xticks(rotation=90, size = 20)
plt.show()

这给出了一个丑陋的情节:

相对于转换后的日期图,如下所示:

df['converted_dates'] = pd.to_datetime(df.dates)

plt.plot(df['converted_dates'], df['values'])
plt.xticks(rotation=90, size = 20)
plt.show()

相关问题