Python - 在图表上绘制多个系列的函数?

Python - A function for plotting multiple series on a graph?

我有一个函数 tasmax_emn(year),它为我提供了一个包含 12 月温度和任何年份日期的 xarray 数据数组。如何在同一张图上绘制多个不同年份(例如 1990-2012)?

一年来,我使用此代码取得了成功:

fig1 = plt.figure(figsize=(15, 15), dpi=200)

ax1 = fig1.add_subplot(1, 1, 1)
ax1.plot(tasmax_emn(1990).time, tasmax_emn(1990), label="1990", linewidth=0.5, color ='k')

ax1.title.set_text('Tasmax ensemble mean')
ax1.set_xlabel('Date')
ax1.set_ylabel('Temperature (degrees C)')
ax1.legend()
plt.grid(True)
plt.show()

如何在不添加另外 21 行代码的情况下绘制从 1990 年到 2012 年的所有年份(我猜是其他函数)?

感谢您的帮助

像这样的东西应该可以工作:

def plot_range(start_year, end_year):
    for year in range(start_year, end_year + 1):
        ax1.plot(tasmax_emn(year).time, tasmax_emn(year), label=str(year), linewidth=0.5, color ='k')

plot_range(1990, 2012)

matplotlib.pyplot中,您可以给出多层值来绘制。一个简单的方法来做你想做的事情,而不需要对你的代码进行太多编辑,就是使用 for 循环:

colors = [...] #List of colors for each year
fig1 = plt.figure(figsize=(15, 15), dpi=200)

ax1 = fig1.add_subplot(1, 1, 1)
for n, year in enumerate(range(1990, 2013)):
    ax1.plot(tasmax_emn(year).time, tasmax_emn(year), label=str(year), linewidth=0.5, color = colors[n])

ax1.title.set_text('Tasmax ensemble mean')
ax1.set_xlabel('Date')
ax1.set_ylabel('Temperature (degrees C)')
ax1.legend()
plt.grid(True)
plt.show()

我认为 Plotly 是最强大的 Python 图形库。 它可以轻松管理子图。

带有子图的图形是使用 plotly.subplots 模块中的 make_subplots 函数创建的。

这是一个子图图表(2x2 网格)的示例:

import plotly.graph_objects as go
from plotly.subplots import make_subplots



fig = make_subplots(
    rows=2, cols=2,
    subplot_titles=("Plot 1", "Plot 2", "Plot 3", "Plot 4"))

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]),
              row=1, col=1)

fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70]),
              row=1, col=2)

fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800]),
              row=2, col=1)

fig.add_trace(go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000]),
              row=2, col=2)

fig.update_layout(height=500, width=700,
                  title_text="Multiple Subplots with Titles")

fig.show()

结果: