Advanced plotting¶
When .plot()
is called on a Timeseries
or Dataset
object, matplotlib axes and fig are returned. Parameters plot_kwargs
and legend_kwargs
can be used to customize the plot.
import matplotlib.pyplot as plt
import gensor as gs
from gensor.testdata import all_paths
gs.set_log_level("WARNING")
pattern = r"[A-Za-z]{2}\d{2}[A-Za-z]{1}|Barodiver"
ds = gs.read_from_csv(path=all_paths, file_format="vanessen", location_pattern=pattern)
Standard plot¶
Standard plotting will work great if you need to quickly check out a dataset that is not too large. With more timeseries, the standard way of potting becomes less performant and the visual suffers.
fig, axs = ds.plot()
plt.show()
Customized plot¶
When you have a large number of timeseries, it would be good to have control over, for example, the shape and location of the legend or the style of the line. Define the settings in two dictionaries and pass them to the .plot()
method.
plot_kwargs = {"linestyle": "--"}
legend_kwargs = {"loc": "center left", "bbox_to_anchor": (1, 0.95), "ncol": 1}
fig, axs = ds.plot(plot_kwargs=plot_kwargs, legend_kwargs=legend_kwargs)
plt.show()
This works exactly the same for a Dataset and for a Timeseries.
fig, axs = ds.filter(location="PB01A", variable="pressure").plot(
plot_kwargs=plot_kwargs, legend_kwargs=legend_kwargs
)
plt.show()
Further customization¶
The tuple returned from .plot() contains fix and an array of axes. We can iterate over them to attach certain properties to all (e.g., adding grid), or retrieve just one and change properties for a particular ax (e.g., add shading under the graph).
def get_axis_by_title(axes, title):
"""Retrieve an axis from an array of axes based on the title text."""
for ax in axes.flat:
if ax.get_title() == title:
return ax
message = f"No axis found with title: '{title}'"
raise ValueError(message)
fig, axs = ds.plot(plot_kwargs=plot_kwargs, legend_kwargs=legend_kwargs)
for ax in axs:
ax.grid(True)
ax.label_outer()
ax_temperature = get_axis_by_title(axs, "Timeseries for Temperature")
x = ax_temperature.get_lines()[0].get_xdata()
y = ax_temperature.get_lines()[0].get_ydata()
ax_temperature.fill_between(x, y, color="skyblue", alpha=0.7)
plt.show()