Skip to content

Commit

Permalink
fix: fix log ticks
Browse files Browse the repository at this point in the history
  • Loading branch information
slaclau committed Sep 15, 2024
1 parent f2a6f40 commit 82e5c84
Show file tree
Hide file tree
Showing 9 changed files with 176 additions and 87 deletions.
1 change: 1 addition & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions .idea/plotly-gtk.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion .idea/watcherTasks.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/plotly_gtk/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import logging

logging.basicConfig()
27 changes: 15 additions & 12 deletions src/plotly_gtk/_chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,16 +85,15 @@ def _draw_gridlines(self, context, width, height, axis):
if "_range" not in self.layout[axis]:
return
if axis.startswith("x"):
self.layout[axis]["_ticksobject"].update_length(
(width - self.layout["_margin"]["l"] - self.layout["_margin"]["r"])
* (self.layout[axis]["domain"][-1] - self.layout[axis]["domain"][0])
)
self.layout[axis]["_ticksobject"].length = (

Check warning on line 88 in src/plotly_gtk/_chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/_chart.py#L88

Added line #L88 was not covered by tests
width - self.layout["_margin"]["l"] - self.layout["_margin"]["r"]
) * (self.layout[axis]["domain"][-1] - self.layout[axis]["domain"][0])

self.layout[axis]["_ticksobject"].calculate()
else:
self.layout[axis]["_ticksobject"].update_length(
(height - self.layout["_margin"]["t"] - self.layout["_margin"]["b"])
* (self.layout[axis]["domain"][-1] - self.layout[axis]["domain"][0])
)
self.layout[axis]["_ticksobject"].length = (

Check warning on line 94 in src/plotly_gtk/_chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/_chart.py#L94

Added line #L94 was not covered by tests
height - self.layout["_margin"]["t"] - self.layout["_margin"]["b"]
) * (self.layout[axis]["domain"][-1] - self.layout[axis]["domain"][0])
self.layout[axis]["_ticksobject"].calculate()
if "anchor" in self.layout[axis] and self.layout[axis]["anchor"] != "free":
anchor = (
Expand Down Expand Up @@ -180,7 +179,9 @@ def _draw_ticks(
+ self.layout[axis]["anchor"][1:]
)
y = self.layout[yaxis]["_range"][0]
x_pos, y_pos = self._calc_pos(x, y, width, height, axis, yaxis)
x_pos, y_pos = self._calc_pos(

Check warning on line 182 in src/plotly_gtk/_chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/_chart.py#L182

Added line #L182 was not covered by tests
x, y, width, height, axis, yaxis, ignore_log_y=True
)
else:
y_pos = self.layout["_margin"]["t"] + (
1 - self.layout[axis]["position"]
Expand All @@ -189,7 +190,7 @@ def _draw_ticks(

for tick, text in zip(x_pos, ticktext):
context.move_to(tick, y_pos)
layout.set_text(text)
layout.set_markup(text)

Check warning on line 193 in src/plotly_gtk/_chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/_chart.py#L193

Added line #L193 was not covered by tests
layout_size = layout.get_pixel_size()
context.rel_move_to(-layout_size[0] / 2, 0)
PangoCairo.show_layout(context, layout)
Expand All @@ -203,7 +204,9 @@ def _draw_ticks(
+ self.layout[axis]["anchor"][1:]
)
x = self.layout[xaxis]["_range"][0]
x_pos, y_pos = self._calc_pos(x, y, width, height, xaxis, axis)
x_pos, y_pos = self._calc_pos(

Check warning on line 207 in src/plotly_gtk/_chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/_chart.py#L207

Added line #L207 was not covered by tests
x, y, width, height, xaxis, axis, ignore_log_x=True
)
else:
x_pos = self.layout["_margin"]["l"] + self.layout[axis]["position"] * (
width - self.layout["_margin"]["l"] - self.layout["_margin"]["r"]
Expand All @@ -212,7 +215,7 @@ def _draw_ticks(

for tick, text in zip(y_pos, ticktext):
context.move_to(x_pos, tick)
layout.set_text(text)
layout.set_markup(text)

Check warning on line 218 in src/plotly_gtk/_chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/_chart.py#L218

Added line #L218 was not covered by tests
layout_size = layout.get_pixel_size()
context.rel_move_to(-layout_size[0], -layout_size[1] / 2)
PangoCairo.show_layout(context, layout)
Expand Down
35 changes: 32 additions & 3 deletions src/plotly_gtk/chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def _update_ranges(self):
for axis in axes:
if "autorange" in self.layout[axis]:
autorange = self.layout[axis]["autorange"]
elif "range" in self.layout[axis] and len(self.layout[axis]["range"] == 2):
if "range" in self.layout[axis] and len(self.layout[axis]["range"]) == 2:

Check warning on line 90 in src/plotly_gtk/chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/chart.py#L90

Added line #L90 was not covered by tests
autorange = False
else:
autorange = True
Expand Down Expand Up @@ -132,6 +132,16 @@ def _update_ranges(self):
_range[0] = _range[0] - 1
_range[-1] = _range[1] + 1
self.layout[axis]["_range"] = _range
else:
if self.layout[axis]["type"] == "log":
self.layout[axis]["_range"] = np.array(

Check warning on line 137 in src/plotly_gtk/chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/chart.py#L136-L137

Added lines #L136 - L137 were not covered by tests
[
10 ** self.layout[axis]["range"][0],
10 ** self.layout[axis]["range"][-1],
]
)
else:
self.layout[axis]["_range"] = np.array(self.layout[axis]["range"])

Check warning on line 144 in src/plotly_gtk/chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/chart.py#L144

Added line #L144 was not covered by tests

# Do matching
matched_to_axes = {
Expand Down Expand Up @@ -159,11 +169,31 @@ def _update_ranges(self):
continue
if self.layout[axis]["_type"] == "log":
self.layout[axis]["_range"] = np.log10(self.layout[axis]["_range"])
range_length = (

Check warning on line 172 in src/plotly_gtk/chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/chart.py#L170-L172

Added lines #L170 - L172 were not covered by tests
self.layout[axis]["_range"][-1] - self.layout[axis]["_range"][0]
)
if (

Check warning on line 175 in src/plotly_gtk/chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/chart.py#L175

Added line #L175 was not covered by tests
"range" in self.layout[axis]
and len(self.layout[axis]["range"]) == 2
):
range_addon = range_length * 0.001

Check warning on line 179 in src/plotly_gtk/chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/chart.py#L179

Added line #L179 was not covered by tests
else:
range_addon = range_length * 0.125 / 2
self.layout[axis]["_range"] = [

Check warning on line 182 in src/plotly_gtk/chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/chart.py#L181-L182

Added lines #L181 - L182 were not covered by tests
self.layout[axis]["_range"][0] - range_addon,
self.layout[axis]["_range"][-1] + range_addon,
]
else:
range_length = (
self.layout[axis]["_range"][-1] - self.layout[axis]["_range"][0]
)
range_addon = range_length * 0.125 / 2
if (

Check warning on line 190 in src/plotly_gtk/chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/chart.py#L190

Added line #L190 was not covered by tests
"range" in self.layout[axis]
and len(self.layout[axis]["range"]) == 2
):
range_addon = range_length * 0.001

Check warning on line 194 in src/plotly_gtk/chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/chart.py#L194

Added line #L194 was not covered by tests
else:
range_addon = range_length * 0.125 / 2

Check warning on line 196 in src/plotly_gtk/chart.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/chart.py#L196

Added line #L196 was not covered by tests
self.layout[axis]["_range"] = [
self.layout[axis]["_range"][0] - range_addon,
self.layout[axis]["_range"][-1] + range_addon,
Expand Down Expand Up @@ -543,7 +573,6 @@ def _update_layout(self):

@staticmethod
def _detect_axis_type(data):
rtn = None
if any(isinstance(i, list) or isinstance(i, np.ndarray) for i in data):
return "multicategory"
if not isinstance(data, np.ndarray):
Expand Down
15 changes: 13 additions & 2 deletions src/plotly_gtk/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"line_1",
"line_2",
]
log_demos = ["log_1"]
log_demos = ["log_1", "log_2"]

Check warning on line 21 in src/plotly_gtk/demo.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/demo.py#L21

Added line #L21 was not covered by tests

demos = {"Scatter": scatter_demos, "log": log_demos}

Check warning on line 23 in src/plotly_gtk/demo.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/demo.py#L23

Added line #L23 was not covered by tests

Expand All @@ -36,6 +36,17 @@ def _get_log_test_figure(reference):
fig = px.scatter(

Check warning on line 36 in src/plotly_gtk/demo.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/demo.py#L33-L36

Added lines #L33 - L36 were not covered by tests
df, x="gdpPercap", y="lifeExp", hover_name="country", log_x=True
)
elif reference == "log_2":
df = px.data.gapminder().query("year == 2007")
fig = px.scatter(

Check warning on line 41 in src/plotly_gtk/demo.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/demo.py#L39-L41

Added lines #L39 - L41 were not covered by tests
df,
x="gdpPercap",
y="lifeExp",
hover_name="country",
log_x=True,
range_x=[1, 100000],
range_y=[0, 100],
)
return fig

Check warning on line 50 in src/plotly_gtk/demo.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/demo.py#L50

Added line #L50 was not covered by tests


Expand Down Expand Up @@ -79,7 +90,7 @@ def test(app):
paned = Gtk.Paned()
window.set_content(paned)

fig = get_test_figure("log_1")
fig = get_test_figure("log_2")

Check warning on line 93 in src/plotly_gtk/demo.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/demo.py#L93

Added line #L93 was not covered by tests
print(fig)
# print(fig["layout"]["template"])

Expand Down
25 changes: 10 additions & 15 deletions src/plotly_gtk/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
:class:`plotly_gtk.chart.PlotlyGtk`."""

import collections
import importlib
import json
import typing

Expand All @@ -22,7 +23,8 @@


def update_dict(d: "GenericType", u: "GenericType") -> "GenericType":
"""Return a copy of :class:`dict` `d` recursively updated with values from :class:`dict` `u`.
"""Return a copy of :class:`dict` `d` recursively updated with values from
:class:`dict` `u`.
Parameters
------
Expand All @@ -35,7 +37,6 @@ def update_dict(d: "GenericType", u: "GenericType") -> "GenericType":
-------
dict
A copy of `d` updated with values from `u`
"""
d = dict(d)
for k, v in u.items():
Expand All @@ -47,8 +48,7 @@ def update_dict(d: "GenericType", u: "GenericType") -> "GenericType":


def parse_color(color: str) -> tuple[float, float, float]:
"""
Return the RGB components of a color provided as a string.
"""Return the RGB components of a color provided as a string.
Parameters
----------
Expand All @@ -73,8 +73,8 @@ def parse_color(color: str) -> tuple[float, float, float]:
def parse_font(
font: dict[str, str | int], single_family: bool = False
) -> Pango.FontDescription:
"""
Parse a dictionary of font parameters and return a :class:`gi.repository.Pango.FontDescription`.
"""Parse a dictionary of font parameters and return a
:class:`gi.repository.Pango.FontDescription`.
Parameters
----------
Expand All @@ -89,7 +89,6 @@ def parse_font(
-------
gi.repository.Pango.FontDescription
The fields are set as provided in the input :class:`dict`.
"""
font = f"{font["family"]} {font["style"]} {font["variant"]} {font["weight"]} {font["size"]}px"
font_desc = Pango.FontDescription.from_string(font)
Expand All @@ -103,8 +102,7 @@ def parse_font(


def get_cartesian_subplots(data: list[dict]) -> list[tuple[str, str]]:
"""
Get the list of cartesian axes pairings with data plotted on them.
"""Get the list of cartesian axes pairings with data plotted on them.
Parameters
----------
Expand All @@ -115,7 +113,6 @@ def get_cartesian_subplots(data: list[dict]) -> list[tuple[str, str]]:
-------
list[tuple[str, str]]
A list of tuples of the form ("xaxis([0-9]+)?", "yaxis([0-9]+)?")
"""
return list(
{
Expand All @@ -129,15 +126,14 @@ def get_cartesian_subplots(data: list[dict]) -> list[tuple[str, str]]:


def get_base_fig() -> dict:
"""
Avoid importing plotly by creating a base figure dictionary.
"""Avoid importing plotly by creating a base figure dictionary.
Returns
-------
dict
The dictionary returned by plotly.graph_object.Figure().to_dict()
"""
template = "potly"
template = "plotly"

Check warning on line 136 in src/plotly_gtk/utils/__init__.py

View check run for this annotation

Codecov / codecov/patch

src/plotly_gtk/utils/__init__.py#L136

Added line #L136 was not covered by tests
file = (
importlib.resources.files(anchor="plotly_gtk.utils")
/ "templates"
Expand All @@ -152,8 +148,7 @@ def get_base_fig() -> dict:


def round_sf(val: float | int, sf: int = 1) -> float:
"""
Round to specified significant figures.
"""Round to specified significant figures.
Parameters
----------
Expand Down
Loading

0 comments on commit 82e5c84

Please sign in to comment.