如果您想将日平均值与月平均值绘制在同一个图上,则可能更容易构建两个数组并将它们都绘制在一组天数上,然后自己处理标签。像这样的
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()
这给了你
或者,您可以使用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()