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

Time:09-29

I have a function, tasmax_emn(year), which gives me an xarray data array containing December temperatures and dates for any year. How do I plot many different years (for example, 1990-2012) on the same plot?

For one year, I have success using this code:

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()

How do I plot all years from 1990 to 2012 without adding another 21 lines of code (I'm guessing some other function)?

Thanks for your help

CodePudding user response:

Something like this should work:

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)

CodePudding user response:

In matplotlib.pyplot You can give multiple layers of values to plot. A simple way to do what you want, without much edit to your code, would be to use a for-loop:

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()

CodePudding user response:

I think Plotly is the most powerful Python graphing library for that kind of thing. It can easily manage subplots.

Figures with subplots are created using the make_subplots function from the plotly.subplots module.

Here is an example of a subplot charts (2x2 grid) :

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()

Result:

enter image description here

  • Related