Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 18 additions & 18 deletions prometheus_api_client/metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,6 @@

from prometheus_api_client.exceptions import MetricValueConversionError

try:
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters

register_matplotlib_converters()
_MPL_FOUND = True
except ImportError as exce: # noqa F841
_MPL_FOUND = False


class Metric:
r"""
A Class for `Metric` object.
Expand Down Expand Up @@ -91,6 +81,9 @@ def __init__(self, metric, oldest_data_datetime=None):
self.start_time = self.metric_values.iloc[0, 0]
self.end_time = self.metric_values.iloc[-1, 0]

# We store the plot information as Class variable
Metric._plot = None

def __eq__(self, other):
"""
Overloading operator ``=``.
Expand Down Expand Up @@ -187,12 +180,19 @@ def __add__(self, other):
error_string = "Different metric labels"
raise TypeError("Cannot Add different metric types. " + error_string)

def plot(self):
_metric_plot = None

def plot(self, *args, **kwargs):
"""Plot a very simple line graph for the metric time-series."""
if _MPL_FOUND:
fig, axis = plt.subplots()
axis.plot_date(self.metric_values.ds, self.metric_values.y, linestyle=":")
fig.autofmt_xdate()
# if matplotlib was not imported
else:
raise ImportError("matplotlib was not found")
if not Metric._metric_plot:
from prometheus_api_client.metric_plot import MetricPlot
Metric._metric_plot = MetricPlot(*args, **kwargs)
metric = self
Metric._metric_plot.plot_date(metric)

def show(self, block=None):
"""Plot a very simple line graph for the metric time-series."""
if not Metric._metric_plot:
# can't show before plot
TypeError("Invalid operation: Can't show() before plot()")
Metric._metric_plot.show(block)
65 changes: 65 additions & 0 deletions prometheus_api_client/metric_plot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""plot code for metric class."""

# This only gets called if there's a plot() call
# This speeds up load time for all the non plot() users
#
# Only loads matplotlib etc during __init__
#

class MetricPlot:
r"""
A Class for `MetricPlot` object.

Internal use only at present

"""

def __init__(self, *args, **kwargs):
"""Functions as a Constructor for the Metric object."""
try:
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters

register_matplotlib_converters()
except ImportError as exce: # noqa F841
raise ImportError("matplotlib was not found")

# One graph with potentially N lines - if plot() is called twice
self._plt = plt
self._fig, self._axis = self._plt.subplots(*args, **kwargs)

def plot_date(self, metric):
"""Plot a very simple line graph for the metric time-series."""

# If we made it here, then we know matplotlib is installed and available
self._axis.plot_date(metric.metric_values.ds, metric.metric_values.y,
linestyle="solid",
label=str(metric.metric_name),
)
self._fig.autofmt_xdate()
# These are provided for documentation reasons only - it's presumptuous for this code to call them
# self._axis.set_xlabel('Date/Time')
# self._axis.set_ylabel('Metric')
# self._axis.set_title('Prometheus')
if len(self._axis.lines) > 1:
# We show a legend (or update the legend) if there's more than line on the plot
self._axis.legend()

def show(self, block=None):
"""convience show() call."""
self._plt.show(block=block)

@property
def plt(self):
""" pyplot value for present plotting """
return self._plt

@property
def axis(self):
""" Axis value for present plotting """
return self._axis

@property
def fig(self):
""" Figure value for present plotting """
return self._fig