在matplotlib中将x轴从几天转换为一个月 [英] Convert x-axis from days to month in matplotlib

查看:65
本文介绍了在matplotlib中将x轴从几天转换为一个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 x 轴,它以天为单位(2 月的 366 天被视为 29 天),但我想将其转换为月份(1 月 - 12 月).我该怎么办...

  def plotGraph():线,点 = getXY()plt.plot(line['xlMax'], c='orangered', alpha=0.5, label = '最低温度 (2005-14)')plt.plot(line ['xlMin'],c ='dodgerblue',alpha = 0.5,label ='最低温度(2005-14)')plt.scatter(point['xsMax'].index, point['xsMax'], s = 10, c = 'maroon', label = 'Record Break Minimum (2015)')plt.scatter(point['xsMin'].index, point['xsMin'], s = 10, c = 'midnightblue', label = 'Record Break Maximum (2015)')ax1 = plt.gca()#主轴ax1.fill_between(line['xlMax'].index, line['xlMax'], line['xlMin'], facecolor='lightgray', alpha=0.25)ax1.grid(真,alpha = 1)对于ax1.spines中的脊椎:ax1.spines [spine] .set_visible(False)ax1.spines ['bottom'].set_visible(True)ax1.spines ['bottom'].set_alpha(0.3)#去除壁虱ax1.tick_params(axis = u'both',which = u'both',length = 0)plt.show()

注意我假设你的天数是 1 到 366;如果它们是0到365,则可能必须更改 range .

但是我认为通常更好的方法是让您的生活融入某种 datetime ;这更灵活,通常也很聪明.如果说你的天数不限于一年,那么将天数与月份关联起来会更加复杂.

此示例使用 datetime 而不是整数.日期直接绘制在 x 轴上,然后使用 matplotlib.dates 中的 DateFormatterMonthLocator 适当地格式化轴:

 将日期时间导入为dt导入matplotlib.pyplot作为plt导入 matplotlib.dates 作为 mdates将numpy导入为npstart = dt.datetime(2016,1,1) #the there must be a year, 即使没有绘制new_dates = [start + dt.timedelta(days=i) for i in range(366)]无花果,ax = plt.subplots()x = 新日期y = np.random.rand(len(range(1,367)))xfmt = mdates.DateFormatter('%b')月 = mdates.MonthLocator()ax.xaxis.set_major_locator(月)ax.xaxis.set_major_formatter(xfmt)ax.plot(x,y)

i have x-axis which is in terms of days (366 days Feb was taken as 29 days) but instead I want to convert it in terms of months (Jan - Dec). What should i do...

def plotGraph():
    line, point = getXY()

    plt.plot(line['xlMax'], c='orangered', alpha=0.5, label = 'Minimum Temperature (2005-14)')
    plt.plot(line['xlMin'], c='dodgerblue', alpha=0.5, label = 'Minimum Temperature (2005-14)')

    plt.scatter(point['xsMax'].index, point['xsMax'], s = 10, c = 'maroon', label = 'Record Break Minimum (2015)')
    plt.scatter(point['xsMin'].index, point['xsMin'], s = 10, c = 'midnightblue', label = 'Record Break Maximum (2015)')

    ax1 = plt.gca() # Primary axes

    ax1.fill_between(line['xlMax'].index , line['xlMax'], line['xlMin'], facecolor='lightgray', alpha=0.25)

    ax1.grid(True, alpha = 1)

    for spine in ax1.spines:
        ax1.spines[spine].set_visible(False)

    ax1.spines['bottom'].set_visible(True)
    ax1.spines['bottom'].set_alpha(0.3)

    # Removing Ticks
    ax1.tick_params(axis=u'both', which=u'both',length=0)

    plt.show()

This is how the graph looks

解决方案

I think the quickest change might be to just set new ticks and tick labels at the starts of months; I found the conversion from day-of-the-year to month here, the first table:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = range(1,367)
y = np.random.rand(len(range(1,367)))

ax.plot(x,y)

month_starts = [1,32,61,92,122,153,183,214,245,275,306,336]
month_names = ['Jan','Feb','Mar','Apr','May','Jun',
               'Jul','Aug','Sep','Oct','Nov','Dec'] 

ax.set_xticks(month_starts)
ax.set_xticklabels(month_names)

Note I assumed your days were numbered 1 to 366; if they are 0 to 365 you may have to change the range.

But I think usually a better approach is to get your days into some sort of datetime; this is more flexible and usually pretty smart. If say, your days were not confined to one year, it would be more complicated to associate day numbers with months.

This example uses datetime instead of integers. The dates are plotted on the x-axis directly, and then the DateFormatter and MonthLocator from matplotlib.dates are used to format the axis appropriately:

import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np

start = dt.datetime(2016,1,1)    #there has to be a year given, even if it isn't plotted
new_dates = [start + dt.timedelta(days=i) for i in range(366)]

fig, ax = plt.subplots()

x = new_dates
y = np.random.rand(len(range(1,367)))

xfmt = mdates.DateFormatter('%b')
months = mdates.MonthLocator()
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(xfmt)

ax.plot(x,y)

这篇关于在matplotlib中将x轴从几天转换为一个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆