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 4492b9b
Show file tree
Hide file tree
Showing 9 changed files with 173 additions and 86 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 = (
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 = (
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(
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)
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(
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)
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:
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(
[
10 ** self.layout[axis]["range"][0],
10 ** self.layout[axis]["range"][-1],
]
)
else:
self.layout[axis]["_range"] = np.array(self.layout[axis]["range"])

# 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 = (
self.layout[axis]["_range"][-1] - self.layout[axis]["_range"][0]
)
if (
"range" in self.layout[axis]
and len(self.layout[axis]["range"]) == 2
):
range_addon = range_length * 0.001
else:
range_addon = range_length * 0.125 / 2
self.layout[axis]["_range"] = [
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 (
"range" in self.layout[axis]
and len(self.layout[axis]["range"]) == 2
):
range_addon = range_length * 0.001
else:
range_addon = range_length * 0.125 / 2
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"]

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

Expand All @@ -36,6 +36,17 @@ def _get_log_test_figure(reference):
fig = px.scatter(
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(
df,
x="gdpPercap",
y="lifeExp",
hover_name="country",
log_x=True,
range_x=[1, 100000],
range_y=[0, 100],
)
return fig


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")
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"
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 4492b9b

Please sign in to comment.