Skip to content

Commit 9a494ea

Browse files
authored
Merge pull request #5719 from robertoffmoura/rm/support-axhline
Convert axhline, axvline, and vertical/horizontal axline to layout shapes
2 parents 224e133 + 99077dc commit 9a494ea

5 files changed

Lines changed: 440 additions & 30 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ This project adheres to [Semantic Versioning](http://semver.org/).
44

55
## Unreleased
66

7+
### Added
8+
- Add support for converting matplotlib reference lines (`axhline`, `axvline`, and horizontal/vertical `axline`) as well as axes-coordinate lines into Plotly layout shapes in `mpl_to_plotly`, including support for date axes [[#5719](https://github.com/plotly/plotly.py/pull/5719)], with thanks to @robertoffmoura for the contribution!
9+
710
### Fixed
811
- Fix `mpl_to_plotly` tick marker mirroring, axis positioning, and trace visibility for twinned and overlaid subplots (such as `twinx` and `twiny`) [[#5310](https://github.com/plotly/plotly.py/pull/5310)], with thanks to @robertoffmoura for the contribution!
912
- Fix `mpl_to_plotly` losing matplotlib axis line colors by exporting the color of each axis's displayed spine to the plotly x and y axis `linecolor` [[#5311](https://github.com/plotly/plotly.py/pull/5311)], with thanks to @robertoffmoura for the contribution!
@@ -15,6 +18,7 @@ This project adheres to [Semantic Versioning](http://semver.org/).
1518
- Fix `mpl_to_plotly` crashing on figures with fully transparent or alpha-carrying colors, such as boxplot outlier markers (`facecolor="none"`), rgba line colors, and `color="none"` text and axis labels; all matplotlib colors are now exported through a single helper that maps `"none"` to transparent rgba and keeps or overrides alpha as matplotlib does [[#5700](https://github.com/plotly/plotly.py/pull/5700)], with thanks to @robertoffmoura for the contribution!
1619
- Export tick label colors to the plotly tickfont in `mpl_to_plotly` [[#5716](https://github.com/plotly/plotly.py/pull/5716)], with thanks to @robertoffmoura for the contribution!
1720
- Fix Plotly Express mutating lists passed to the `x` or `y` arguments in wide mode [[#5727](https://github.com/plotly/plotly.py/pull/5727)], with thanks to @cpruijsen for the contribution!
21+
- Fix `convert_dash` mapping dotted lines (`linestyle=':'`) to invalid `'circle'` in Plotly, correctly converting them to `'dot'` and preserving custom dash patterns as pixel lists, [[#5719](https://github.com/plotly/plotly.py/pull/5719)] with thanks to @robertoffmoura for the contribution!
1822
- Fix `px.sunburst`, `px.treemap` and `px.icicle` listing sectors in a different order on every run when `path` is used with a Polars DataFrame; sectors now follow their order of first appearance for all dataframe backends [[#5766](https://github.com/plotly/plotly.py/pull/5766)], with thanks to @Irahan2 for the contribution!
1923
- Fix `mpl_to_plotly` conversion of matplotlib contour lines and line collections: close contour rings ending with `Z` codes, support dash styles, convert date x-axes, separate disjoint subpaths with `None` separators, hide line collection traces from the legend by default, and group consecutive same-style lines into single traces [[#5770](https://github.com/plotly/plotly.py/pull/5770)], with thanks to @robertoffmoura for the contribution!
2024

‎plotly/matplotlylib/mplexporter/exporter.py‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -84,12 +84,6 @@ def process_transform(
8484
Data transformed to match the given coordinate code.
8585
Returned only if data is specified
8686
"""
87-
if isinstance(transform, transforms.BlendedGenericTransform):
88-
warnings.warn(
89-
"Blended transforms not yet supported. "
90-
"Zoom behavior may not work as expected."
91-
)
92-
9387
if force_trans is not None:
9488
if data is not None:
9589
data = (transform - force_trans).transform(data)

‎plotly/matplotlylib/mpltools.py‎

Lines changed: 29 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -57,34 +57,40 @@ def check_corners(inner_obj, outer_obj):
5757
return True
5858

5959

60+
VALID_DASH = {"solid", "dot", "dash", "longdash", "dashdot", "longdashdot"}
61+
62+
6063
def convert_dash(mpl_dash):
6164
"""Convert mpl line symbol to plotly line symbol and return symbol."""
65+
if not mpl_dash:
66+
return "solid"
6267
if mpl_dash in DASH_MAP:
6368
return DASH_MAP[mpl_dash]
64-
else:
65-
dash_array = mpl_dash.split(",")
69+
if mpl_dash in VALID_DASH:
70+
return mpl_dash
71+
if mpl_dash in ("dashed", "--"):
72+
return "dash"
73+
if mpl_dash in ("dotted", ":"):
74+
return "dot"
75+
76+
dash_array = mpl_dash.replace("px", "").replace(" ", "").split(",")
77+
cleaned = ",".join(dash_array)
78+
if cleaned in DASH_MAP:
79+
return DASH_MAP[cleaned]
6680

67-
if len(dash_array) < 2:
68-
return "solid"
81+
if len(dash_array) < 2:
82+
return "solid"
6983

70-
# Catch the exception where the off length is zero, in case
71-
# matplotlib 'solid' changes from '10,0' to 'N,0'
72-
if math.isclose(float(dash_array[1]), 0.0):
73-
return "solid"
84+
try:
85+
off = float(dash_array[1])
86+
except ValueError:
87+
return "solid"
7488

75-
# If we can't find the dash pattern in the map, convert it
76-
# into custom values in px, e.g. '7,5' -> '7px,5px'
77-
dashpx = ",".join([x + "px" for x in dash_array])
89+
if math.isclose(off, 0.0):
90+
return "solid"
7891

79-
# TODO: rewrite the convert_dash code
80-
# only strings 'solid', 'dashed', etc allowed
81-
if dashpx == "7.4px,3.2px":
82-
dashpx = "dashed"
83-
elif dashpx == "12.8px,3.2px,2.0px,3.2px":
84-
dashpx = "dashdot"
85-
elif dashpx == "2.0px,3.3px":
86-
dashpx = "dotted"
87-
return dashpx
92+
# Convert custom dash pattern into px list (e.g. '7,5' -> '7px,5px')
93+
return ",".join([x + "px" for x in dash_array])
8894

8995

9096
def convert_path(path):
@@ -603,10 +609,12 @@ def mpl_dates_to_datestrings(dates, mpl_formatter):
603609
DASH_MAP = {
604610
"10,0": "solid",
605611
"6,6": "dash",
606-
"2,2": "circle",
612+
"2,2": "dot",
607613
"4,4,2,4": "dashdot",
608614
"none": "solid",
609615
"7.4,3.2": "dash",
616+
"12.8,3.2,2.0,3.2": "dashdot",
617+
"2.0,3.3": "dot",
610618
}
611619

612620
PATH_MAP = {

‎plotly/matplotlylib/renderer.py‎

Lines changed: 125 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,21 @@
77
88
"""
99

10+
import math
1011
import warnings
1112

1213
import matplotlib.patches as mpatches
14+
from matplotlib import lines as mlines
15+
from matplotlib import transforms
1316
import plotly.graph_objs as go
1417
from plotly.matplotlylib.mplexporter import Renderer
1518
from plotly.matplotlylib import mpltools
16-
17-
1819
from plotly.matplotlylib.mpltools import _export_color
1920

21+
# Artist class created by ``Axes.axline``: ``AxLine`` in matplotlib >= 3.8,
22+
# ``_AxLine`` in earlier versions.
23+
_AXLINE_CLASS = getattr(mlines, "AxLine", None) or getattr(mlines, "_AxLine", ())
24+
2025

2126
def _per_path(values, i, default):
2227
"""Return the style value for the i-th path of a path collection.
@@ -550,9 +555,11 @@ def draw_marked_line(self, **props):
550555
marked_line["x"] = self._convert_x_dates(marked_line["x"])
551556
self.plotly_fig.add_trace(marked_line)
552557
self.msg += " Heck yeah, I drew that line\n"
553-
elif props["coordinates"] == "axes":
558+
elif props["coordinates"] == "axes" and self._processing_legend:
554559
# dealing with legend graphical elements
555560
self.msg += " Using native legend\n"
561+
elif self._is_axes_reference_line(props) and self._draw_axes_line(props):
562+
pass
556563
else:
557564
self.msg += " Line didn't have 'data' coordinates, not drawing\n"
558565
warnings.warn(
@@ -561,6 +568,121 @@ def draw_marked_line(self, **props):
561568
"coordinates!"
562569
)
563570

571+
def _is_axes_reference_line(self, props):
572+
"""Check whether a line qualifies as an axes-coordinate reference line
573+
(e.g. axhline, axvline, horizontal/vertical axline, or a 2-point
574+
segment drawn with ``transform=ax.transAxes``) that can be drawn as a
575+
2-point layout shape."""
576+
if not props.get("linestyle") or len(props.get("data", [])) != 2:
577+
return False
578+
if props["coordinates"] == "axes" and not self._processing_legend:
579+
return True
580+
if props["coordinates"] == "display" and isinstance(
581+
props["mplobj"].get_transform(), transforms.BlendedGenericTransform
582+
):
583+
return True
584+
return False
585+
586+
def _draw_axes_line(self, props):
587+
"""Draw an axes-coordinate reference line as a layout shape.
588+
589+
axhline/axvline and horizontal/vertical axline span the axes domain
590+
along one axis and sit at a data value on the other. Segments in axes
591+
coordinates keep their exact endpoints in axes domain coordinates.
592+
Returns True when a shape is drawn."""
593+
if not props.get("linestyle") or len(props.get("data", [])) != 2:
594+
return False
595+
ax = self.current_mpl_ax
596+
line = props["mplobj"]
597+
trans = line.get_transform()
598+
599+
axis_suffix = str(self.axis_ct) if self.axis_ct > 1 else ""
600+
x_axis = "x{0}".format(axis_suffix)
601+
y_axis = "y{0}".format(axis_suffix)
602+
x_domain = "{0} domain".format(x_axis).strip()
603+
y_domain = "{0} domain".format(y_axis).strip()
604+
605+
if isinstance(trans, transforms.BlendedGenericTransform) and (
606+
trans == ax.get_yaxis_transform() or trans._x == ax.transAxes
607+
):
608+
# axhline: x spans the axes domain [xmin, xmax], y is in data coordinates
609+
x_data = line.get_xdata(orig=False)
610+
y_data = line.get_ydata(orig=False)
611+
x0, x1 = float(x_data[0]), float(x_data[1])
612+
y0, y1 = float(y_data[0]), float(y_data[1])
613+
xref = x_domain
614+
yref = y_axis
615+
elif isinstance(trans, transforms.BlendedGenericTransform) and (
616+
trans == ax.get_xaxis_transform() or trans._y == ax.transAxes
617+
):
618+
# axvline: x is in data coordinates, y spans the axes domain [ymin, ymax]
619+
x_data = line.get_xdata(orig=False)
620+
y_data = line.get_ydata(orig=False)
621+
x0, x1 = float(x_data[0]), float(x_data[1])
622+
y0, y1 = float(y_data[0]), float(y_data[1])
623+
if self.x_is_mpl_date:
624+
x0, x1 = self._convert_x_dates([x0, x1])
625+
xref = x_axis
626+
yref = y_domain
627+
elif props["coordinates"] == "axes" and not isinstance(line, _AXLINE_CLASS):
628+
# Segment fixed to the axes (e.g. transform=ax.transAxes): props["data"]
629+
# holds its endpoints as axes fractions, which map directly onto the
630+
# axes domain, so the segment keeps its extent and stays put on pan/zoom
631+
(x0, y0), (x1, y1) = [(float(x), float(y)) for x, y in props["data"]]
632+
xref = x_domain
633+
yref = y_domain
634+
else:
635+
# general reference line (e.g. horizontal or vertical axline)
636+
if props["coordinates"] == "display":
637+
px_points = props["data"]
638+
elif props["coordinates"] == "axes":
639+
px_points = [ax.transAxes.transform(pt) for pt in props["data"]]
640+
else:
641+
px_points = [trans.transform(pt) for pt in props["data"]]
642+
(x0, y0), (x1, y1) = [
643+
ax.transData.inverted().transform(pt) for pt in px_points
644+
]
645+
646+
dx = x1 - x0
647+
dy = y1 - y0
648+
if math.isclose(dy, 0.0, abs_tol=1e-12):
649+
# Horizontal line: use x domain so it spans the chart, y in data coordinates
650+
x0, x1 = 0.0, 1.0
651+
y0, y1 = float(y0), float(y1)
652+
xref = x_domain
653+
yref = y_axis
654+
elif math.isclose(dx, 0.0, abs_tol=1e-12):
655+
# Vertical line: use y domain so it spans the chart, x in data coordinates
656+
y0, y1 = 0.0, 1.0
657+
if self.x_is_mpl_date:
658+
x0, x1 = self._convert_x_dates([x0, x1])
659+
else:
660+
x0, x1 = float(x0), float(x1)
661+
xref = x_axis
662+
yref = y_domain
663+
else:
664+
return False
665+
666+
color = _export_color(props["linestyle"]["color"], props["linestyle"]["alpha"])
667+
shape = go.layout.Shape(
668+
type="line",
669+
x0=x0,
670+
y0=y0,
671+
x1=x1,
672+
y1=y1,
673+
xref=xref,
674+
yref=yref,
675+
line=go.layout.shape.Line(
676+
color=color,
677+
width=props["linestyle"]["linewidth"],
678+
dash=mpltools.convert_dash(props["linestyle"]["dasharray"]),
679+
),
680+
layer="above",
681+
)
682+
self.plotly_fig["layout"]["shapes"] += (shape,)
683+
self.msg += " Heck yeah, I drew that reference line\n"
684+
return True
685+
564686
def draw_image(self, **props):
565687
"""Draw image.
566688

0 commit comments

Comments
 (0)