根据相同的x值绘制两个不同长度的matplotlib列表

2024-06-26 17:40:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个numpy.ndarraysbcmonthlydailyavg。你知道吗

bcmonthly has a length of 12 and shape of (12,)

dailyavg has a length of 364 and shape of (364,)

bcmonthy是月平均值,dailyavg是日平均值。我想画12个月的坐标轴。你知道吗

绘图bcmonthly没有问题,因为它的形状是12。但是,当我同时绘制dailyavg时,我得到以下错误:

ValueError: x and y must have same first dimension, but have shapes (12,) and (364,)

下面是我的代码:

fig = plt.figure()  
ax1=fig.add_subplot(111)
ax1.plot(months,bcmonthly,'r') #months is a list months=['jan','feb',..etc]
ax2 = ax1.twinx()
ax2.plot(months, dailyavg)   
plt.show()

Tags: andofplothavefigpltlength平均值
2条回答

如果要将日平均数与月平均数绘制在同一个图上,则可以更轻松地构造两个数组,并根据天数数组绘制它们,然后自己处理标记。像这样的

import matplotlib.pyplot as plt
import numpy as np

bcmonthly = np.random.rand(12)    # Creates some random example data,
dailyavg = np.random.rand(365)    # use your own data in place of this
days = np.linspace(0, 364, 365)
months = ['January', 'February', 'March', 'April', 'May',
          'June', 'July', 'August', 'September',
          'October', 'November', 'December']

lmonths = [0, 2, 4, 6, 7, 9, 11]
smonths = [3, 5, 8, 10]
month_idx = list()
idx = -15      # Puts the month avg and label in the center of the month
for jj in range(len(months)):
    if jj in lmonths:
        idx += 31
        month_idx.append(idx)
    elif jj in smonths:
        idx += 30
        month_idx.append(idx)
    elif jj == 1:
        idx += 28
        month_idx.append(idx)

fig = plt.figure(figsize=(10,4), dpi=300)  
plt.plot(month_idx,bcmonthly,'r')
plt.plot(days, dailyavg, ':', linewidth=1)
plt.xlim([-1,366])
plt.title("Monthly and Daily Averages")
plt.xticks(month_idx, months, rotation=45)
plt.show()

这给了你 Daily and Monthly averages

或者,您可以使用面向对象的方法ax.plot(),但这需要您分别指定记号标签和位置

import matplotlib.pyplot as plt
import numpy as np

bcmonthly = np.random.rand(12)
dailyavg = np.random.rand(365)
days = np.linspace(0, 364, 365)
months = ['January', 'February', 'March', 'April', 'May',
          'June', 'July', 'August', 'September',
          'October', 'November', 'December']

lmonths = [0, 2, 4, 6, 7, 9, 11]
smonths = [3, 5, 8, 10]
month_idx = list()
idx = -15      # Puts the month avg and label in the center of the month
for jj in range(len(months)):
    if jj in lmonths:
        idx += 31
        month_idx.append(idx)
    elif jj in smonths:
        idx += 30
        month_idx.append(idx)
    elif jj == 1:
        idx += 28
        month_idx.append(idx)

fig = plt.figure(figsize=(10,4), dpi=300)  
ax1 = fig.add_subplot(111)
ax1.plot(month_idx,bcmonthly,'r')
ax2 = ax1.twinx()
ax2.plot(days, dailyavg, ':', linewidth=1)
plt.xlim([-1,366])
plt.title("Monthly and Daily Averages")
ax1.set_xticklabels(months, rotation=45)
ax1.set_xticks(month_idx)
plt.show()

当绘制monthsdailyavg时,您需要扩展months使其长度为364 Matplotlib不能为您决定months中的12个x值中的哪一个分配364个日平均值,但是您可以自己通过制作一个适当长度的x值列表来提供该信息。你知道吗

所以,在本例中,这似乎意味着创建一个包含"January"31次,然后"February"28次的列表,依此类推。。。直到长度达到364(取决于错过哪一天?)你知道吗

相关问题 更多 >