Skip to content

Commit

Permalink
Use self.fig.tight_layout to avoid cut-off labels (#1055)
Browse files Browse the repository at this point in the history
This PR closes #739, calling tight_layout on the new self.fig attribute inside the finalize methods of Postag, ConfusionMatrix, ClassificationReport, JointPlot, and FeatureImportances to avoid having labels get cut off
  • Loading branch information
rebeccabilbro committed Apr 9, 2020
1 parent bc2c316 commit 4737f0f
Show file tree
Hide file tree
Showing 12 changed files with 29 additions and 21 deletions.
4 changes: 2 additions & 2 deletions docs/api/classifier/confusion_matrix.rst
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,9 @@ Class names can be added to a ``ConfusionMatrix`` plot using the ``label_encoder
:alt: ConfusionMatrix plot with class names

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split as tts
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split as tts

from yellowbrick.classifier import ConfusionMatrix

iris = load_iris()
Expand All @@ -88,7 +89,6 @@ Class names can be added to a ``ConfusionMatrix`` plot using the ``label_encoder

iris_cm.fit(X_train, y_train)
iris_cm.score(X_test, y_test)

iris_cm.show()

Quick Method
Expand Down
1 change: 0 additions & 1 deletion docs/api/text/postag.rst
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,6 @@ The same functionality above can be achieved with the associated quick method ``

# Create the visualizer, fit, score, and show it
postag(machado)
plt.tight_layout()


Part of Speech Tags
Expand Down
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
16 changes: 11 additions & 5 deletions tests/test_text/test_postag.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@
##########################################################################

import pytest
import matplotlib.pyplot as plt

from yellowbrick.exceptions import YellowbrickValueError
from yellowbrick.text.postag import *
from tests.base import VisualTestCase
import matplotlib.pyplot as plt
from tests.base import IS_WINDOWS_OR_CONDA

from yellowbrick.text.postag import *
from yellowbrick.exceptions import YellowbrickValueError

try:
import nltk
Expand Down Expand Up @@ -176,7 +178,9 @@ def test_quick_method(self):
viz = postag(tagged_docs, ax=ax, show=False)
viz.ax.grid(False)

self.assert_images_similar(viz)
# Fails on Miniconda/Appveyor with images not close (RMS 5.157)
tol = 5.5 if IS_WINDOWS_OR_CONDA else 0.25
self.assert_images_similar(viz, tol=tol)

def test_unknown_tagset(self):
"""
Expand Down Expand Up @@ -229,7 +233,9 @@ def test_frequency_mode(self):
# Assert that ticks are set properly
assert ticks_ax == sorted_tags

self.assert_images_similar(ax=ax, tol=0.5)
# Fails on Miniconda/Appveyor with images not close (RMS 5.302)
tol = 5.5 if IS_WINDOWS_OR_CONDA else 0.5
self.assert_images_similar(ax=ax, tol=tol)

@pytest.mark.skipif(nltk is None, reason="test requires nltk")
def test_word_tagged(self):
Expand Down
4 changes: 1 addition & 3 deletions yellowbrick/classifier/class_prediction_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
##########################################################################

import numpy as np
import matplotlib.pyplot as plt

from sklearn.utils.multiclass import unique_labels
from sklearn.metrics.classification import _check_targets
Expand Down Expand Up @@ -229,8 +228,7 @@ def finalize(self, **kwargs):
self.ax.set_ylim(0, cmax + cmax * 0.1)

# Ensure the legend fits on the figure
plt.tight_layout(rect=[0, 0, 0.90, 1]) # TODO: Could use self.fig now

self.fig.tight_layout(rect=[0, 0, 0.90, 1])

##########################################################################
## Quick Method
Expand Down
14 changes: 7 additions & 7 deletions yellowbrick/classifier/classification_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ def finalize(self, **kwargs):
self.ax.set_xticklabels(self._displayed_scores, rotation=45)
self.ax.set_yticklabels(self.classes_)

plt.tight_layout() # TODO: Could use self.fig now
self.fig.tight_layout()


def classification_report(
Expand Down Expand Up @@ -314,24 +314,24 @@ def classification_report(
not a classifier, an exception is raised. If the internal model is not
fitted, it is fit when the visualizer is fitted, unless otherwise specified
by ``is_fitted``.
X_train : ndarray or DataFrame of shape n x m
A feature array of n instances with m features the model is trained on.
Used to fit the visualizer and also to score the visualizer if test splits are
not directly specified.
y_train : ndarray or Series of length n
An array or series of target or class values. Used to fit the visualizer and
also to score the visualizer if test splits are not specified.
X_test : ndarray or DataFrame of shape n x m, default: None
An optional feature array of n instances with m features that the model
is scored on if specified, using X_train as the training data.
y_test : ndarray or Series of length n, default: None
An optional array or series of target or class values that serve as actual
labels for X_test for scoring purposes.
ax : matplotlib Axes, default: None
The axes to plot the figure on. If not specified the current axes will be
used (or generated if required).
Expand Down Expand Up @@ -407,7 +407,7 @@ def classification_report(
)
else:
visualizer.score(X_train, y_train)

# Draw the final visualization
if show:
visualizer.show()
Expand Down
3 changes: 3 additions & 0 deletions yellowbrick/classifier/confusion_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,9 @@ def finalize(self, **kwargs):
self.ax.set_ylabel("True Class")
self.ax.set_xlabel("Predicted Class")

# Call tight layout to maximize readability
self.fig.tight_layout()


##########################################################################
## Quick Method
Expand Down
2 changes: 1 addition & 1 deletion yellowbrick/features/jointplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ def finalize(self, **kwargs):
plt.sca(self.ax)

# Call tight layout to maximize readability
plt.tight_layout()
self.fig.tight_layout()

def _index_into(self, idx, data):
"""
Expand Down
3 changes: 1 addition & 2 deletions yellowbrick/model_selection/importances.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@

import warnings
import numpy as np
import matplotlib.pyplot as plt

from yellowbrick.draw import bar_stack
from yellowbrick.base import ModelVisualizer
Expand Down Expand Up @@ -288,7 +287,7 @@ def finalize(self, **kwargs):
self.ax.grid(False, axis="y")

# Ensure we have a tight fit
plt.tight_layout()
self.fig.tight_layout()

def _find_classes_param(self):
"""
Expand Down
3 changes: 3 additions & 0 deletions yellowbrick/text/postag.py
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,9 @@ def finalize(self, **kwargs):
)
)

# Call tight layout to maximize readability
self.fig.tight_layout()

def show(self, outpath=None, **kwargs):
if outpath is not None:
kwargs["bbox_inches"] = kwargs.get("bbox_inches", "tight")
Expand Down

0 comments on commit 4737f0f

Please sign in to comment.